我更改了模拟服务方法的返回值后,第二个expect
语句出现问题。我已经尝试过fakeAsync
和Jasmine的done
,但仍然失败,它仅适用于我显然想摆脱的setTimeout
。
不起作用:
const authServiceMock = {
getSessionEvents: jasmine.createSpy('getSessionEventsSpy').and.returnValue(of()),
getAvailableCalculators: jasmine.createSpy('getAvailableCalculators')
};
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [],
providers: [{provide: AppAuthService, useValue: authServiceMock}],
declarations: [AppComponent]
}).compileComponents();
}));
it('should check for available calculators after login', fakeAsync(() => {
component.ngOnInit();
expect(authServiceMock.getAvailableCalculators).not.toHaveBeenCalled();
authServiceMock.getSessionEvents.and.returnValue(of(SESSION_EVENTS.login));
tick(1000);
expect(authServiceMock.getAvailableCalculators).toHaveBeenCalled(); // <=== FAILS
}));
工作:
it('should check for available calculators after login', () => {
component.ngOnInit();
expect(authServiceMock.getAvailableCalculators).not.toHaveBeenCalled();
authServiceMock.getSessionEvents.and.returnValue(of(SESSION_EVENTS.login));
setTimeout(() => expect(authServiceMock.getAvailableCalculators).toHaveBeenCalled(), 1000); // <=== PASSES
});
我看不到您的组件代码,但是在黑暗中拍照,请尝试以下方法:
[fixture.whenStable()
等到诺言完成。
it('should check for available calculators after login', async(done) => {
component.ngOnInit();
expect(authServiceMock.getAvailableCalculators).not.toHaveBeenCalled();
authServiceMock.getSessionEvents.and.returnValue(of(SESSION_EVENTS.login));
await fixture.whenStable();
expect(authServiceMock.getAvailableCalculators).toHaveBeenCalled();
done();
});