【发布时间】:2020-08-19 07:17:53
【问题描述】:
我有一个从 api 加载一些数据的组件,但我只需要一次这些数据,所以我不使用 reducer 和选择器。 我只使用 api 调用的动作和效果
这就是我要测试的代码:
private loadData() {
const subscriptions: Subscription = new Subscription();
subscriptions.add(
this.actions$
.pipe(ofType(EApiActions.ApiLoaded))
.subscribe((action: ApiLoaded) => {
subscriptions.unsubscribe();
this.data = action.result;
})
);
subscriptions.add(
this.actions$
.pipe(ofType(EApiActions.ApiFailure))
.subscribe((action: ApiFailure) => {
subscriptions.unsubscribe();
})
);
this.store.dispatch(
new ApiRequest()
);
}
我的测试如下所示:
let mockStore: MockStore;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
providers: [
provideMockActions(() => actions$),
provideMockStore({ initialState })
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
mockStore = TestBed.inject(MockStore);
});
it('should dispatch action and enter the result|failure actionhandler', () => {
// Arrange
const expectedAction = new ApiRequest();
const dispatchSpy = spyOn(mockStore, 'dispatch');
// Act
fixture.detectChanges();
// Assert
expect(dispatchSpy).toHaveBeenCalledWith(expectedAction);
// Act - test success
mockStore.dispatch(new ApiLoaded([]));
fixture.detectChanges();
// Assert
expect(component.data).not.toBeNull();
});
测试一直有效到这一行 expect(dispatchSpy).toHaveBeenCalledWith(expectedAction);
正如您所看到的,该组件侦听 EApiActions.ApiLoaded 所以我尝试使用 mockStore.dispatch(new ApiLoaded([]));但什么也没发生,我的组件中的代码没有被执行
我该如何解决这个问题? 这是我如何使用动作和效果的有效方式吗?还是您认为我应该始终检查一个将结果保存到商店的减速器,然后我可以使用选择器访问它?
【问题讨论】:
-
loadData()方法是否有条件调用?还是只是在某个 ng 钩子中调用(例如 ngOnInit)? -
是的,我在 ngOnInit 上调用它
-
actions$的值是多少?也许它的值应该是TestBed.inject(ScannedActionsSubject)。 -
谢谢!这对我来说是正确的提示,现在我的测试工作正常。
标签: angular typescript unit-testing ngrx