【问题标题】:Testing NGRX/effect with jest - test is always passing用玩笑测试 NGRX/效果 - 测试总是通过
【发布时间】:2020-03-01 17:25:46
【问题描述】:

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

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

【问题讨论】:

    标签: angular jestjs ngrx-effects


    【解决方案1】:

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

    因为这是一个异步测试,所以需要使用回调/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
        });
      });
    

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      相关资源
      最近更新 更多