我有一个具有以下功能的组件:
onClearSearch() {
this.store$.dispatch(some action);
}
尝试对组件进行单元测试并触发商店调度不起作用。我的组件测试如下:
let store: MockStore<State>;
beforeEach(waitForAsync(() => {
TestBed.configureTestModule({
...
providers: [
SearchStoreEffects,
provideMockActions(() => actions$),
provideMockStore({initialState, selectors: [...]})
],
...
}).compileComponents();
...
store = TestBed.inject(MockStore);
fixture.detectChanges();
}));
it('should clear search value', () => {
const storeSpy = spyOn(store, 'dispatch').and.callThrough();
component.onClearSearch();
fixture.detectChanges();
expect(storeSpy).toHaveBeenCalledTimes(1);
});
测试总是失败,并且测试被称为零次。我想念什么?
答案 0 :(得分:1)
如果我将 it 断言包装在 fakeAsync 中,然后在 component.onClearSearch(); 之后调用 tick,它就可以工作
答案 1 :(得分:0)
您需要监视组件实例
it('should clear search value', () => {
const storeSpy = spyOn(component.store$, 'dispatch').and.callThrough();
component.onClearSearch();
fixture.detectChanges();
expect(storeSpy).toHaveBeenCalledTimes(1);
});