对NgRx效果进行单元测试以确保调用该服务方法-不起作用

时间:2019-01-21 15:19:03

标签: angular unit-testing jestjs ngrx ngrx-effects

我正在使用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))
      )
    )
  );
}

那是一个简单的测试。如您所见,它应该会失败,但总是会失败。 我在这里在StackOverflow How to unit test this effect (with {dispatch: false})?上遵循了类似的问题,但是它对我不起作用,就好像代码执行从未进入效果。$ 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
    });
  });
});

以防万一我对动作做傻了,这是动作文件: 我很可能不是,因为它可以按预期在应用中运行。

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;

================================================= =======

我已经使用了来自ngrx官方文档https://ngrx.io/guide/effects/testing的示例,现在我可以成功在下面输入subscription块,同时记录了两个控制台日志,但是测试成功。真奇怪我尝试从订阅块抛出错误,但测试仍然成功。

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
    });
  });

1 个答案:

答案 0 :(得分:3)

好,所以我知道了。为了成功测试是否从NgRx效果中调用了特定的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();
  });

await effects.$fetchApisPaths.subscribe();阻止执行并在下一行运行测试断言。

现在,当我尝试运行expect(true).toBe(false);来测试测试是否失败时,它会正确地失败。

问题中我的代码存在问题(例如在ngrx docs https://ngrx.io/guide/effects/testing中使用ReplaySubject的示例)是,当断言位于.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
});  

因此代码执行在第 2)行停止,测试用例返回正数,而在第 3)行永不执行。

因此,在.subscribe()块内有断言的ngrx docs中的测试用例将始终为绿色,从而给您的测试用例带来了误判。这是我在ngrx ^7.0.0

中遇到的行为