开玩笑地测试 NGRX/effect - 测试总是通过

Testing NGRX/effect with jest - test is always passing

我创建了一个效果测试,但测试总是通过

@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 - 测试也通过了。 请帮忙。 谢谢

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

因为是异步测试,所以需要使用callback/helperdone,像这样:

 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
    });
  });