Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 角度2-模拟-响应为空_Unit Testing_Angular_Mocking_Jasmine - Fatal编程技术网

Unit testing 角度2-模拟-响应为空

Unit testing 角度2-模拟-响应为空,unit-testing,angular,mocking,jasmine,Unit Testing,Angular,Mocking,Jasmine,Angular 2.0.0-Ionic 2 RC0-Npm 3.10.8-Node v4.5.0-Karma 1.3.0-Jasmine 2.5.2 上一个问题: 我现在在执行npm测试时遇到一个新错误:null不是对象(计算'\u this.events.length') 这是由以下代码触发的:if(this.events.length>0){在EventsPage中,这意味着我在events.spec.ts中设置的响应不知何故没有正确返回 我不太会嘲笑安格拉尔,所以这很可能是新手犯的错误

Angular 2.0.0-Ionic 2 RC0-Npm 3.10.8-Node v4.5.0-Karma 1.3.0-Jasmine 2.5.2

上一个问题:


我现在在执行
npm测试时遇到一个新错误:
null不是对象(计算'\u this.events.length')

这是由以下代码触发的:
if(this.events.length>0){
在EventsPage中,这意味着我在
events.spec.ts
中设置的响应不知何故没有正确返回

我不太会嘲笑安格拉尔,所以这很可能是新手犯的错误

(更改了前一个问题中的一些代码,因此我将重新发布它们)

事件页面

import { Component } from '@angular/core';

import { NavController, Loading, LoadingController } from 'ionic-angular';

import { APICaller } from '../../services/apicaller.service';
import { EventDetailComponent } from '../event-detail/event-detail.component';
import { Event } from '../../models/event.model';

/*
  Class for Evenementen Overzicht.
*/
@Component({
  selector: 'events-component',
  templateUrl: 'events.component.html',
  providers: [ APICaller ]
})

 /** -------------------------------------------------------------------------------------- */

    export class EventsPage {

    //list of all events
    public events : Array<Event>;
    //the event that has been clicked on the page
    public selectedEvent : Event;
    //boolean to show 'no events' error message
    public noEvents:boolean;

     /** -------------------------------------------------------------------------------------- */

      constructor(public navCtrl : NavController, public apiCaller:APICaller, public loadingCtrl : LoadingController) {
        //retrieve all events --> async method, can't use this.events yet.
        this.getEvents();
      }

      /** -------------------------------------------------------------------------------------- */

      /**Get Events - Sets the 'events' variable to all events found by the API. */
      getEvents(){
        //setup a loadingscreen (broke testing so removed for now)
       // let loading = this.loadingCtrl.create({
        //  content: "Loading..."
       // }); 
        //present the loadingscreen
       // loading.present();

        //reset the noEvents boolean.
        this.noEvents = true;

        //call the api and get all events
        this.apiCaller.getEvents()
        .subscribe(response => {

          console.log("RESP:"+response);
          //response is list of events
          this.events = response;
          //if the event is not empty, set noEvents to false.

          if(this.events.length > 0){ //<----------------------------FAILS HERE
            this.noEvents = false;
          }
          //close the loading message.
         // loading.dismiss();
        });
      }
    }
MockAPICaller

import { SpyObject } from './helper';
import { APICaller } from '../apicaller.service';
import Spy = jasmine.Spy;

export class MockAPICaller extends SpyObject {
    getEventsSpy: Spy;
    searchEventSpy:Spy;
    getParticipantSpy:Spy;
    getEventParticipantsSpy:Spy;
    searchEventParticipantSpy:Spy;
    addNewCommentSpy:Spy;
    updateCommentSpy:Spy;
    deleteCommentSpy:Spy;
    getUsernameSpy:Spy;
    presentSuccessMessageSpy:Spy;

    fakeResponse:any;

    constructor(){
        super( APICaller );
        this.fakeResponse = null;
        this.getEventsSpy = this.spy('getEvents').andReturn(this);
        this.searchEventSpy = this.spy('searchEvent').andReturn(this);
        this.getParticipantSpy = this.spy('getParticipant').andReturn(this);
        this.getEventParticipantsSpy = this.spy('getEventParticipant').andReturn(this);
        this.searchEventParticipantSpy = this.spy('searchEventParticipant').andReturn(this);
        this.addNewCommentSpy = this.spy('addNewComment').andReturn(this);
        this.updateCommentSpy = this.spy('updateComment').andReturn(this);
        this.deleteCommentSpy = this.spy('deleteComment').andReturn(this);
        this.getUsernameSpy = this.spy('getUsername').andReturn(this);
        this.presentSuccessMessageSpy = this.spy('presentSuccessMessage').andReturn(this);
    }

    subscribe(callback: any){
        callback(this.fakeResponse);
    }

    setResponse(json:any):void{
        this.fakeResponse = json;
    }
}

在创建组件之前,您应该在mock上设置响应。您正在组件构造函数中调用
getEvents
,而mock尚未设置数据

it('should return all events', () => {
  mockAPICaller.setResponse(JSON.stringify(`[{
    id: 4,
    title: 'Weekend',
    eventdate: '24/09/2016',
    kind: 'closed',
    startingtime: '18:00',
    endtime: '21:00',
    description: 'Go Home'
  }]`));
  let fixture = TestBed.createComponent(EventsPage);
  let eventsPage = fixture.debugElement.componentInstance;
  fixture.detectChanges();
  eventsPage.getEvents();
  fixture.detectChanges();
  console.log(eventsPage.events);
});

在创建组件之前,您应该在mock上设置响应。您正在组件构造函数中调用
getEvents
,而mock尚未设置数据

it('should return all events', () => {
  mockAPICaller.setResponse(JSON.stringify(`[{
    id: 4,
    title: 'Weekend',
    eventdate: '24/09/2016',
    kind: 'closed',
    startingtime: '18:00',
    endtime: '21:00',
    description: 'Go Home'
  }]`));
  let fixture = TestBed.createComponent(EventsPage);
  let eventsPage = fixture.debugElement.componentInstance;
  fixture.detectChanges();
  eventsPage.getEvents();
  fixture.detectChanges();
  console.log(eventsPage.events);
});

再次感谢,您可能还知道如何解决此错误吗?:
undefined不是构造函数(评估'response.json()')
从哪里得到的?啊,它不在这段代码中,我认为mockApi只返回了json stirng,所以在订阅
EventPage
时,我添加了
.json()
到响应的末尾,因为我正在返回一个Json字符串so
this.events=response.Json();
而不是
this.events=response;
只要让模拟对象有一个返回对象的
Json()
函数。
setResponse({Json:function(){return theObject;})
再次感谢,您可能也知道如何解决此错误吗?:
未定义不是构造函数(评估'response.json()')
您从哪里得到的?啊,它不在这段代码中,我认为mockApi只返回了json stirng,所以在订阅
事件页面时,我添加了
.json()
到响应的末尾,因为我正在返回一个Json字符串so
this.events=response.Json();
而不是
this.events=response;
只要让模拟对象有一个返回对象的
Json()
函数。
setResponse({Json:function(){return theObject;}})