我正在为我的组件编写单元测试。我想测试/覆盖我要在我的订阅中调用函数calculateJohnDoe的部分。请参考以下内容:
ngOnInit(): void {
this.authStore$ = this.store.select('auth');
this.authStore$.subscribe(authData => {
if (authData && authData.myprop) {
this.calculateJohnDoe();
}
});
}
我要在规范中尝试做的事情如下:
describe(..., () => {
let mockStore: MockStore<AuthState>;
// Testbed configuration
providers: [ Store ]
}).compileComponents();
mockStore = TestBed.get(Store);
...
it('should call the function', () => {
mockStore.setState({
myprop: true
});
const spy = jest.spyOn(LoginComponent.prototype, 'calculateJohnDoe');
expect(spy).toHaveBeenCalled();
});
...
});
但是问题是我从来没有在组件ts文件中得到myprop真正更新的存储事件/ callack。
答案 0 :(得分:1)
您可以创建一个代表您的商店的模拟服务,此类将模拟具有属性_anObservable
的可观察主题:
class MockService {
_anObservable = new Subject();
select(prop: string) {
return this._anObservable.asObservable();
}
}
describe(..., () => {
// Testbed configuration
providers: [
{ provide: YourStore, useClass: MockService }
]
...
it('should call the function', inject([YourStore], (store) => {
const spy = jest.spyOn(LoginComponent.prototype, 'calculateJohnDoe');
store._anObservable.next({
myprop: true
});
expect(spy).toHaveBeenCalled();
}));
...
});