我创建了一个效果测试,但该测试始终通过
@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-测试也将通过。请帮忙。谢谢
问题在于,在您的测试中,订阅主体从未被调用。
因为这是异步测试,所以需要使用回调/帮助器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
});
});