用玩笑测试NGRX /效果-测试始终通过

时间:2019-11-05 10:42:16

标签: angular jestjs ngrx-effects

我创建了一个效果测试,但该测试始终通过

@Injectable()
export class myEffects {
  @Effect()
  getEffect$ = this.actions$.pipe(
    ofType(MyActionTypes.Get),
    switchMap((action: GetAction) =>
      this.myService
        .get()
        .map((data) => new GetSuccessAction(data))
        .catch((res) => of(new GetFailedAction(res)))
    )
  );

  constructor(private actions$: Actions<MyActions>, public myService: MyService) {}
}
describe('myEffects', () => {
  let actions$: ReplaySubject<any>;
  let effects: myEffects;
  let myService = {
    get: jest.fn()
  };

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        myEffects,
        provideMockActions(() => actions$),
        {
          provide: MyService,
          useValue: myService
        }]
    });
    effects = TestBed.get<myEffects>(myEffects);
  });

  it('aaa', () => {
    const data = {};

    myService.get.mockReturnValue(data);

    actions$ = new ReplaySubject(1);
    actions$.next(new GetAction());

    effects.getEffect$.subscribe((action) => {
      expect(action).toEqual({
        type: MyActionTypes.GetFailed,
        payload: data
      });
    });
  });
});

仅当效果触发器的类型为GetSuccess时,测试才应通过,但将期望类型设置为GetFailed-测试也将通过。 请帮忙。 谢谢

1 个答案:

答案 0 :(得分:1)

问题在于,在您的测试中,订阅主体从未被调用。

由于这是异步测试,因此需要使用回调/帮助程序done,如下所示:

 it('aaa', async done => { // <== here
    const data = {};

    myService.get.mockReturnValue(data);

    actions$ = new ReplaySubject(1);
    actions$.next(new GetAction());

    effects.getEffect$.subscribe((action) => {
      expect(action).toEqual({
        type: MyActionTypes.GetFailed,
        payload: data
      });
      done(); // <== and here, the test will only pass when the subscription is called
    });
  });