我的组件中有各种方法订阅注入依赖项中的方法,这些方法返回可观察对象。
我想编写 Jest 单元测试以确保当这些可观察对象返回/错误时,我的方法会做正确的事情。
在下面的示例中,我正在尝试编写一个检查是否doAThing
已触发的测试。以下测试均无效。他们都因错误而失败,例如
'returnMyObservable.subscribe 不是函数'。
// Example method to test component
public testFunction (): void {
this.myService.returnMyObservable.subscribe(
( value ) => this.doAThing( value )
)
}
describe( 'myComponemt', () => {
let fixture;
let myServiceMock;
beforeEach( () => {
myServiceMock = {
returnMyObservable: fn()
}
fixture = new myComponent( myServiceMock );
});
// 1) I have tried mocking with a returned value
it ( 'should call do a thing when value is returned', () => {
myServiceMock.returnMyOnservable.mockReturnValue( true );
fixture.testFunction();
expect( fixture.doAThing ).toHaveBeenCalled();
});
// 2) I have tried returning an observable
it ( 'should call do a thing when value is returned', () => {
myServiceMock.returnMyOnservable.mockReturnValue( of( true ) );
fixture.testFunction();
expect( fixture.doAThing ).toHaveBeenCalled();
});
});