带订阅的单元测试嵌套服务

时间:2020-02-27 16:18:05

标签: angular unit-testing

我正在尝试对一项服务进行单元测试,该服务的方法返回void,但在其中调用另一个服务并对其进行预订。 问题是我不断收到错误: this.secondService.getPage 不是一个函数。 我在做什么错了?

这就是我正在测试的服务的样子:

public jumpTo(arg1: any, arg2: any): void {

     this.secondService.getPage(arg01: any, arg02: any).subscribe(response => {
       // do stuff
     })

  }

我的规格文件如下所示:

describe('NavigationService', () => {
    let navigation: NavigationService
    let secondServiceSpy: any

    beforeEach(() => {

        secondServiceSpy = jasmine.createSpyObj('SecondService', ['getPage'])
        TestBed.configureTestingModule({
            providers: [
                NavigationService,
                { provide: SecondService, useValue: secondServiceSpy }
            ]
        })
        navigation = TestBed.get(NavigationService)
    })

    it('should jump to another step', () => {
        navigation.jumpTo('value1', 'value2' )
        expect(secondServiceSpy.getPage).toHaveBeenCalled()
    })
})

2 个答案:

答案 0 :(得分:1)

import { of } from 'rxjs/observable/of';
....
describe('NavigationService', () => {
    let navigation: NavigationService
    let secondServiceSpy: any
    let secondService: SecondService; // add this variable

    beforeEach(() => {

        secondServiceSpy = jasmine.createSpyObj('SecondService', ['getPage'])
        TestBed.configureTestingModule({
            providers: [
                NavigationService,
                { provide: SecondService, useValue: secondServiceSpy }
            ]
        })
        navigation = TestBed.get(NavigationService)
        secondService = TestBed.get(SecondService); // populate the value
    })

    it('should jump to another step', () => {
        // make the function return an observable.
        secondServiceSpy.getPage.and.returnValue(of(...)); // whatever you to return for the subscribe
        navigation.jumpTo('value1', 'value2' )
        expect(secondServiceSpy.getPage).toHaveBeenCalled();
        // I don't know if the expect of above is a good assertion or will work
        // You should do assertions of what happens in the subscribe block.
    });

答案 1 :(得分:0)

您应在fakeAsync区域中执行单元测试。

import { fakeAsync, flush } from '@angular/core/testing';
...
it('should jump to another step', fakeAsync(() => {
    navigation.jumpTo('value1', 'value2' );
    flush(); 
    expect(secondServiceSpy.getPage).toHaveBeenCalled();
}));

有关更多信息,请咨询https://angular.io/api/core/testing/fakeAsynchttps://angular.io/api/core/testing/flush