我一直在努力使它工作数小时。这是我第一个转换为Jest而不是Karma的项目,到目前为止一切顺利。尽管出于某种原因,我还是去为自己的效果编写了一些测试,但是我完全无法按照我期望的方式对其进行测试。
我要测试的效果是一种非常简单的导航方式:
print(df)
#> # A tibble: 50 x 1
#> price
#> <dbl>
#> 1 5000
#> 2 40000
#> 3 25000
#> 4 15000
#> 5 15000
#> 6 5000
#> 7 15000
#> 8 15000
#> 9 15000
#> 10 40000
#> # ... with 40 more rows
```
我注入了一个伪造的路由器,并打算测试它是否调用了导航,该测试经历了多次迭代以使其正常工作,但是我目前拥有的是:
@Effect({ dispatch: false })
go$ = this.actions$.pipe(
ofType(RouterActions.GO),
tap(
({ payload: { path, query: queryParams, extras } }: RouterActions.Go) => {
this.router.navigate(path, { queryParams, ...extras });
}
)
);
运行该测试时,在终端上得到以下结果:
describe('Router Effects', () => {
let actions$: Observable<any>;
let router: TestRouter;
let effects: RouterEffects;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
RouterEffects,
provideMockActions(() => actions$),
{
provide: Router,
useFactory: getRouter
}
]
});
actions$ = TestBed.get(Actions);
router = TestBed.get(Router);
effects = TestBed.get(RouterEffects);
});
describe('go$', () => {
test('should call router.navigate with the correct path', done => {
const action = new fromActions.Go({ path: ['some', 'path'] });
actions$ = hot('-a', { a: action });
const expected = cold('-b', { b: action });
effects.go$.subscribe(
result => {
console.log('inside subscribe?');
expect(router.navigate).toHaveBeenCalled();
console.log('after expect');
done();
console.log('after done?');
},
done,
done
);
expect(effects.go$).toBeObservable(expected);
});
});
});
我一直在努力弄清楚为什么未调用异步回调?我在此处复制了一个最小的仓库:https://github.com/BenAychh/example-ngrx-effects-jest,相关代码位于此文件夹https://github.com/BenAychh/example-ngrx-effects-jest/tree/master/src/app/store/effects中。如果有人有兴趣在这里帮助我,您应该可以克隆整个仓库,然后运行它,并(希望)看到我所看到的。
答案 0 :(得分:0)
鉴于此效果:
@Injectable()
export class AuthEffects {
@Effect({ dispatch: false })
public logoutSuccess$ = this.actions$.pipe(
ofType(AuthActionTypes.LogoutSuccess),
tap(() => this.localStorage.removeItem(AUTH_FEATURE_KEY)),
tap(() => this.router.navigate(['/']))
);
}
这是我测试dispatch: false
效果的方法:
describe('logoutSuccess$', () => {
it('should navigate and remove related data from local storage', () => {
const action = new LogoutSuccess;
actions$ = cold('-a', { a: action });
expect(effects.logoutSuccess$).toBeObservable(actions$);
expect(localStorageService.removeItem).toHaveBeenCalledWith(AUTH_FEATURE_KEY);
expect(router.navigate).toHaveBeenCalledWith(['/']);
});
});
.toBeObservable(actions$)
可以解决问题。
基于this answer。