【问题标题】:How to mock ngrx action in Angular component?如何在 Angular 组件中模拟 ngrx 动作?
【发布时间】:2019-11-29 09:55:21
【问题描述】:
//init函数上的组件代码
this.rootStore.dispatch(new action1());
在效果中我调用了“action1Success”
我在组件中有 action1Success 和订阅功能的管道
//组件代码
this.actionListener$.pipe( ofType( MyactionTypes.action1Success)).subscribe((success: SuccessObj) => { });
【问题讨论】:
标签:
angular
unit-testing
karma-runner
ngrx
effects
【解决方案1】:
您可以使用 provideMockActions
import { provideMockActions } from '@ngrx/effects/testing';
...
describe('RouterHistoryEffects', () => {
let actions: ReplaySubject<any>;
let effects: YourEffects;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideMockActions(() => actions)
]
});
....
你的测试应该是这样的
// dispatch your action
(actions$ as ReplaySubject).next({ type: '[Users] Get Users' })
// subscribe to the Effect stream
effects.getUsers$.subscribe(action => {
expect(action).toEqual({
type: '[Users API] action1Success',
users: [...],
});
});