具有存储调度操作的 Angular 单元测试组件

tla*_*rea 6 javascript unit-testing ngrx angular

我有一个具有以下功能的组件:

onClearSearch() {
  this.store$.dispatch(some action);
}
Run Code Online (Sandbox Code Playgroud)

尝试对组件进行单元测试并触发商店调度不起作用。我的组件测试如下所示:

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);
});
Run Code Online (Sandbox Code Playgroud)

测试总是失败,测试被调用次数为零。我缺少什么?

Owe*_*vin 7

您需要监视组件实例

it('should clear search value', () => {
  const storeSpy = spyOn(component.store$, 'dispatch').and.callThrough();
  component.onClearSearch();
  fixture.detectChanges();
  expect(storeSpy).toHaveBeenCalledTimes(1);
});
Run Code Online (Sandbox Code Playgroud)


tla*_*rea 4

如果我将 it 断言包装在 fakeAsync 中,然后在 component.onClearSearch(); 之后调用 tick,它就可以工作