我在组件中有各种方法订阅注入依赖项中返回 observables 的方法。
我想编写 Jest 单元测试,以确保当这些 observables 返回 / 出错时,我的方法可以正确执行。
在下面的示例中,我试图编写一个测试,检查 doAThing
是否已触发。以下两个测试都不起作用。它们都会失败,并出现类似于
'returnMyObservable.subscribe is not a function'.
// 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();
});
});
of(value)
模拟服务函数以返回我选择的可观察对象。我只是在其中调用执行订阅的组件,使用toHaveBeenCalled()
测试doAThing
函数,并在测试用例的末尾添加了done()
。使用这种设置似乎所有测试都通过了。 - Qarun Qadir Bissoondial