如何对 Action 是否已发送进行单元测试?
例如,在 LogoutService 中,我有这个简单的方法:
logout(username: string) {
store.dispatch([new ResetStateAction(), new LogoutAction(username)]);
}
我需要编写一个单元测试来验证这两个操作是否已分派(dispatch):
it('should dispatch ResetState and Logout actions', function () {
logoutService.logout();
// how to check the dispactched actions and their parameters?
// expect(...)
});
如何检查已调度的操作?
最佳答案
使用 Jasmine spy
我相信在单元测试中,所有相关依赖项的实际实现都应该被模拟,因此我们不应该在这里包含任何实际的存储。
在这里,我们为 Store 提供了一个 jasmine spy,并且只是检查是否使用正确的参数调度了某些操作。这也可以用于提供 stub 数据。
describe('LogoutService', () => {
let storeSpy: jasmine.SpyObj<Store>;
beforeEach(() => {
storeSpy = jasmine.createSpyObj(['dispatch']);
TestBed.configureTestingModule({
providers: [LogoutService, { provide: Store, useValue: storeSpy }]
});
})
it('should dispatch Logout and Reset actions', () => {
storeSpy.dispatch.withArgs([
jasmine.any(ResetStateAction),
jasmine.any(LogoutAction)])
.and
.callFake(([resetAction, logoutAction]) => {
expect(resetAction.payload).toEqual({...something});
expect(logoutAction.payload).toEqual({...somethingElse});
});
TestBed.inject(LogoutService).logout();
});
关于angular - NGXS:如何测试一个 Action 是否被调度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51088421/