cod*_*pic 5 unit-testing jestjs ngrx ngrx-effects angular
我正在使用 NgRx ^7.0.0 版本。这是我的 NgRx 效果类:
import { Injectable } from '@angular/core';
import { ApisService } from '../apis.service';
import { Effect, Actions, ofType } from '@ngrx/effects';
import { Observable } from 'rxjs';
import { ApisActionTypes, ApisFetched } from './apis.actions';
import { mergeMap, map } from 'rxjs/operators';
@Injectable()
export class ApisEffects {
constructor(private apisS: ApisService, private actions$: Actions) { }
@Effect()
$fetchApisPaths: Observable<any> = this.actions$.pipe(
ofType(ApisActionTypes.FetchApisPaths),
mergeMap(() =>
this.apisS.fetchHardCodedAPIPaths().pipe(
map(res => new ApisFetched(res))
)
)
);
}
Run Code Online (Sandbox Code Playgroud)
这是一个简单的测试。如您所见,它应该失败,但总是通过。我在 StackOverflow 上遵循了类似的问题如何对这种效果进行单元测试(使用 {dispatch: false})?但它对我不起作用,好像代码执行永远不会进入 effects.$fetchApisPaths.subscribe 块
import { TestBed } from '@angular/core/testing';
import { provideMockActions } from '@ngrx/effects/testing';
import { hot, cold } from 'jasmine-marbles';
import { Observable, ReplaySubject } from 'rxjs';
import { ApisEffects } from '../state/apis.effects';
import { ApisFetch, ApisFetched } from '../state/apis.actions';
import { IApiPath } from '../models';
import { convertPaths, getAPIPathsAsJson, ApisService } from '../apis.service';
import { ApisServiceMock } from './mocks';
describe('Apis Effects', () => {
let effects: ApisEffects;
let actions: Observable<any>;
let apisS: ApisService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
ApisEffects,
provideMockActions(() => actions),
{
provide: ApisService,
useClass: ApisServiceMock
}
]
});
effects = TestBed.get(ApisEffects);
apisS = TestBed.get(ApisService);
});
it('should call ApisService method() to get Api Paths', () => {
const spy = spyOn(apisS, 'fetchHardCodedAPIPaths');
const action = new ApisFetch();
actions = hot('--a-', {a: action});
effects.$fetchApisPaths.subscribe(() => {
console.log('%c effect trigerred', 'color: orange; border: 1px solid red;');
// expect(spy).toHaveBeenCalled();
expect(true).toBe(false); // never fails
});
});
});
Run Code Online (Sandbox Code Playgroud)
以防万一我用动作做傻事,这里是动作文件:很可能我不是,因为它按预期在应用程序中工作。
import { Action } from '@ngrx/store';
import { IApiPath } from '../models';
export enum ApisActionTypes {
FetchApisPaths = '[Apis] Fetch Paths',
FetchedApisPaths = '[Apis] Fetched Paths'
}
export class ApisFetch implements Action {
readonly type = ApisActionTypes.FetchApisPaths;
}
export class ApisFetched implements Action {
readonly type = ApisActionTypes.FetchedApisPaths;
constructor(public payload: IApiPath[]) {}
}
export type ApisActions = ApisFetch | ApisFetched;
Run Code Online (Sandbox Code Playgroud)
========================编辑========================== ====
我使用了来自官方 ngrx 文档https://ngrx.io/guide/effects/testing的示例,现在我可以成功进入下面的订阅块,我记录了两个控制台日志,但测试成功。这很奇怪!我尝试从订阅块抛出错误,但测试仍然成功。
it('should work also', () => {
actions$ = new ReplaySubject(1);
actions$.next(new ApisFetch());
effects.$fetchApisPaths.subscribe(result => {
console.log('will be logged');
expect(true).toBe(false); // should fail but nothing happens - test succeeds
console.log(' --------- after '); // doesn't get called, so the code
// execution stops on expect above
});
});
Run Code Online (Sandbox Code Playgroud)
好的,所以我让它工作了。为了成功测试是否从 NgRx effect 中调用了特定的 Angular 服务方法,我将一个测试用例包装在一个async:
it('should call ApisService method to fetch Api paths', async () => {
const spy = spyOn(apisS, 'fetchHardCodedAPIPaths');
actions$ = new ReplaySubject(1);
actions$.next(new ApisFetch());
await effects.$fetchApisPaths.subscribe();
expect(spy).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
Iawait effects.$fetchApisPaths.subscribe();阻止执行并在下一行运行测试断言。
现在,当我尝试运行expect(true).toBe(false);以测试测试是否失败时,它正确地失败了。
问题中我的代码的问题(ReplaySubject如 ngrx 文档https://ngrx.io/guide/effects/testing 中的示例)是当断言在.subscribe()块内时不可能使测试失败。那里发生了一些不确定的事情,我仍然不知道为什么代码会以以下方式运行:
effects.$fetchApisPaths.subscribe(result => {
console.log('will be logged'); // 1) gets logged
expect(true).toBe(false); // 2) should fail
console.log(' - after '); // 3) doesn't get called
});
Run Code Online (Sandbox Code Playgroud)
所以代码执行在第2)行停止,测试用例返回正值,第3)行永远不会被执行。
因此,在.subscribe()块内带有断言的 ngrx 文档中的测试用例将始终为绿色,从而为您的测试用例提供误报。这是我经历过的行为ngrx ^7.0.0
编辑 2020 年 9 月 - 针对 ngrx 版本 9 进行了更新。如果上述解决方案对您或将来对我不起作用,因为我再次面临同样的问题,只能找到我自己的答案来提供帮助和来自@Christian 的精彩评论为了引导我提出 ngrx gitter 问题,请尝试以下方法:
it('should call ApisService method to fetch Api paths', async () => {
const spy = spyOn(apisS, 'fetchHardCodedAPIPaths');
actions$ = cold('--a-', {
a: ControlCenterTrendsLineChartPeriodChange({ numberOfMonths: 24 })
});
await effects.$fetchApisPaths.subscribe();
expect(actions$).toSatisfyOnFlush(() => {
expect(spy).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3341 次 |
| 最近记录: |