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

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

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

qwer123456asdf 回答:用玩笑测试NGRX /效果-测试始终通过

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

由于这是异步测试,因此需要使用回调/帮助程序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
    });
  });
本文链接:https://www.f2er.com/3160320.html

大家都在问