带有可观察量的Angular 2测试组件

时间:2017-01-24 06:09:16

标签: unit-testing angular karma-jasmine

我正在测试角度组件,代码是

ngOnInit(): void {
        this.getNar();
    }

    getNar(): void {
        let self = this;
        this.dashboardService.getNar().subscribe(
            res => self.narIds = res.narIds,
            error => self.error = error,
            function () {
                self.narIds.forEach(element => {
                   // Some Code
                });
            }
        );
    }

这种仪表板服务的服务提供商是

  getNar(): Observable<any> {
    return this.http.get(Config.Api.GetNar + '1/nar').map((res: Response) => res.json());
  }

我的测试用例是:

let res = '"narIds":[{"id":1,"narId":"104034-1","narName":"SDLC Platform"},{"id":2,"narId":"64829-1","narName":"EMS-EMS"}]';

describe('Application Health Component', () => {
    beforeEach( async(() => {
       TestBed.configureTestingModule({
            providers: [MockBackend, DashboardService],
            imports: [ChartsModule, SlimScrollModule, HttpModule],
            declarations: [CompletedFilterPipe, ApplicationHealthComponent]
        })
            .compileComponents()
            .then(createComponent);
    }));

    it('should call the getNar when ngOnInit is called', async(() => {
        spyOn(dashboardService, 'getNar').and.returnValue(Observable.of(res));
        comp.ngOnInit();
        expect(dashboardService.getNar).toHaveBeenCalled();
    }));
});

function createComponent() {
    fixture = TestBed.createComponent(ApplicationHealthComponent);
    comp = fixture.componentInstance;
    dashboardService = fixture.debugElement.injector.get(DashboardService);
};

我遇到的问题是测试用例给出了一个错误,即forEach未定义。

enter image description here

1 个答案:

答案 0 :(得分:1)

错误信息不是forEach函数没有定义,它是你的对象&#34; self.narIds&#34;未定义。相当肯定这是由于你在Observable.subscribe

中声明你的onComplete函数的方式

与此Rx Subscribe OnComplete fires but cannot use the data

相关

改变你的

() => {
    self.narIds.forEach(element => {
    // Some Code
 });

代码

{{1}}