NGXS:测试分派的动作不适用于 ofActionDispatched
Posted
技术标签:
【中文标题】NGXS:测试分派的动作不适用于 ofActionDispatched【英文标题】:NGXS: Testing dispatched action is not working with ofActionDispatched 【发布时间】:2019-04-29 09:21:02 【问题描述】:我正在尝试测试动作调度,但它在我的测试中不起作用... 组件表现正常,action 被调度,但是 actions$.pipe 没有捕捉到 action,所以无法在测试中检查。
代码:
describe('ResponsiveService', () =>
let store, actions$;
const observableMediaMock =
subscribe : (callback: (change: MediaChange) => void) =>
this.callback = callback
,
triggerMediaChange: (change: MediaChange) => this.callback(change)
;
beforeEach(() =>
TestBed.configureTestingModule(
imports: [
FlexLayoutModule,
NgxsModule.forRoot([MediaState])
],
providers: [ResponsiveService, provide: ObservableMedia, useValue: observableMediaMock ]
);
store = TestBed.get(Store);
actions$ = TestBed.get(Actions);
);
it('should be created', inject([ResponsiveService], (service: ResponsiveService) =>
expect(service).toBeTruthy();
));
it("should send get request", function(done)
inject([ResponsiveService], (service: ResponsiveService) =>
const mediaQueryValue = 'mediaQuery',
mqAliasValue = 'mqAlias',
suffixValue = 'suffix';
actions$.pipe(ofActionDispatched([MediaChanged]))
.subscribe((payload) =>
expect(payload).toBeTruthy();
expect(payload.mediaQuery).toEqual(mediaQueryValue);
done();
);
service.init();
observableMediaMock.triggerMediaChange(new MediaChange(null, mediaQueryValue, mqAliasValue, suffixValue));
)(); // function returned by 'inject' has to be invoked
);
);
谢谢!
【问题讨论】:
【参考方案1】:将您的测试更新为以下内容:
it("should send get request", async( () =>
inject([ResponsiveService], (service: ResponsiveService) =>
const mediaQueryValue = 'mediaQuery',
mqAliasValue = 'mqAlias',
suffixValue = 'suffix';
actions$.pipe(ofActionDispatched(MediaChanged))
.subscribe((payload) =>
expect(payload).toBeTruthy();
expect(payload.mediaQuery).toEqual(mediaQueryValue);
);
service.init();
observableMediaMock.triggerMediaChange(new MediaChange(null, mediaQueryValue, mqAliasValue, suffixValue));
)(); // function returned by 'inject' has to be invoked
));
ofActionDispatched
不接受列表作为输入,但评估者接受项目列表,例如:ofActionDispatched(MediaChanged, SomeOtherAction)
。
您还应该能够删除 done 函数并将测试包装在普通的 async
块中。希望这会有所帮助,不确定我是否正确打开和关闭了所有括号。
【讨论】:
太棒了,非常感谢!还有异步提示,再次感谢!以上是关于NGXS:测试分派的动作不适用于 ofActionDispatched的主要内容,如果未能解决你的问题,请参考以下文章