Angular 使用jest测试NGRX/效果-测试始终通过
我创建了一个效果测试,但测试总是通过的Angular 使用jest测试NGRX/效果-测试始终通过,angular,jestjs,ngrx-effects,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 GetSucc
@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) {}
}
@Injectable()
导出类myEffects{
@效果()
getEffect$=此.actions$.pipe(
类型(MyActionTypes.Get),
开关映射((操作:GetAction)=>
这是我的服务
.get()
.map((数据)=>new GetSuccessAction(数据))
.catch((res)=>of(新GetFailedAction(res)))
)
);
构造函数(私有操作$:操作,公共myService:myService){}
}
description('myEffects',()=>{
let actions$:ReplaySubject;
let效应:myEffects;
让我的服务={
get:jest.fn()
};
在每个之前(()=>{
TestBed.configureTestingModule({
供应商:[
我的影响,
provideMockActions(()=>actions$),
{
提供:MyService,
useValue:myService
}]
});
effects=TestBed.get(myEffects);
});
它('aaa',()=>{
常量数据={};
myService.get.mockReturnValue(数据);
动作$=新的ReplaySubject(1);
actions$.next(新的GetAction());
effects.getEffect$.subscribe((操作)=>{
期望(行动)。toEqual({
类型:MyActionTypes.GetFailed,
有效载荷:数据
});
});
});
});
仅当效果触发器的类型为GetSuccess,但将expect类型设置为GetFailed时,测试才应通过-测试也应通过。
请帮忙。
谢谢问题是在您的测试中从未调用订阅主体 因为这是一个异步测试,所以需要使用回调/helper
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
});
});
it('aaa',异步完成=>{//{
期望(行动)。toEqual({
类型:MyActionTypes.GetFailed,
有效载荷:数据
});
完成()//
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
});
});