【问题标题】:How to test ngrx/effects with Jasmine / Karma with Angular5, ngrx5?如何使用 Angular5、ngrx5 使用 Jasmine / Karma 测试 ngrx/效果?
【发布时间】:2018-06-13 15:29:58
【问题描述】:

这是我需要测试的文件。 我正在使用 Angular5 (^5.2.0)、ngrx5 (^5.2.0),目前我的注意力集中在一些效果服务上。 这是我当前需要测试的代码。 但是我不知道如何正确实施它,我做了一些尝试,但它们只是失败了。你们有安比的秘诀吗?谢谢

import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';
import { FETCH_DATA } from '../reducers/data.reducer';
import { DataService } from './data.service';
import { Subject } from 'rxjs/Subject';
import { ActionWithPayload } from '../types/app-actions';

@Injectable()
export class AutoCompleteEffects {
  public autoComplete$ = new Subject<{
    type: string;
    payload: { results: string[]; searchValue: string };
  }>();

  @Effect()
  getData$ = this.actions$.ofType(FETCH_DATA).switchMap((action: ActionWithPayload) => {
    return this.data
      .getData(action.payload)
      .map(results => ({
    type: 'FETCHED_DATA',
    payload: { results, searchValue: action.payload }
      }))
      .catch(() =>
    Observable.of({
      type: 'FETCHED_DATA',
      payload: { results: [], searchValue: action.payload }
    })
      );
  });


  constructor(
    private actions$: Actions,
    private data: DataService,
  ) {
    this.getData$.subscribe(action => this.autoComplete$.next(action));
  }

  public getAutoCompleteEffects() {
    return this.autoComplete$.asObservable();
  }
}

【问题讨论】:

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


    【解决方案1】:

    有几样东西是你需要的

    1. 使用 provideMockActions 遵循 ngrx 效果测试设置(请参阅 this
    2. 模拟 DataService 并注入它

    之后,只是不同动作的测试

    it('should suggest auto complete values', () => {
      actions = of([<test-actions>]);
      const expectedEffects = of([<expected-actions-from-effects>]);
    
      expect(TestBed.get(AutoCompleteEffects).getData$).toBeObservable(expectedEffects);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-16
      • 2018-01-04
      • 2019-02-06
      • 2021-04-07
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 2018-06-09
      相关资源
      最近更新 更多