unit-testing - 带有 ngrx 的 angular 2 组件 - 运行单元测试时出错

标签 unit-testing jasmine ngrx

我正在从事 Angular 2 项目,使用 ngrx(用于 Redux 逻辑)和 rxjs(用于可观察)。

现在我尝试通过运行自动创建的 .spec.ts 文件来测试项目。

部分测试失败,所有测试都是使用 Store(来自 ngrx)的组件测试。 这是其中之一:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { MyComponent } from './overlay-menu-item.component';

describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [ MyComponent ],
  })
  .compileComponents();
}));

beforeEach(() => {
  fixture = TestBed.createComponent(MyComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

it('should create', () => {
  expect(component).toBeTruthy();
});
});

我查了一下问题,错误是:

No provider to Store

所以我补充:(我用jasmine做测试)

 beforeEach(async(() => {
TestBed.configureTestingModule({
  declarations: [ MyComponent ],
  providers: [Store]
 })
 .compileComponents();
}));

现在我得到了其他错误:

No provider for StateObservable

所以我补充说:

  beforeEach(async(() => {
TestBed.configureTestingModule({
  declarations: [ MyComponent ],
  providers: [Store, StateObservable]
 })
 .compileComponents();
}));

但现在我遇到了新的错误,我不知道如何处理它:

Failed: Can't resolve all parameters for StateObservable: (?).
    Error: Can't resolve all parameters for StateObservable: (?).
        at syntaxError [mywebprojectPath]/node_modules/@angular/compiler/@angular/compiler.es5.js:1689:22)

我该怎么办?

最佳答案

你应该创建一个 MockStore .

简而言之:

import { Action } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { map } from 'rxjs/operator/map';

export class MockStore<T> extends BehaviorSubject<T> {  
  constructor(private _initialState: T) {
    super(_initialState);
  }
  dispatch = (action: Action): void => {
  }

  select = <T, R>(pathOrMapFn: any, ...paths: string[]): Observable<R> => {
    return map.call(this, pathOrMapFn);
  }
}

然后您可以在测试中提供 mockStore:

const initialState = {...};
TestBed.configureTestingModule({
  ...
  providers:[
    {provide:Store, useValue: new MockStore(initialState)}
  ]
  ...
})

关于unit-testing - 带有 ngrx 的 angular 2 组件 - 运行单元测试时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46544604/

相关文章:

javascript - D3JS 测试 - enter() 未被触发

unit-testing - PHPUnit:如何模拟具有多个参数且没有直接顺序的多个方法调用?

python - Pytest monkeypatch 不适用于导入的函数

angular - 输入 Jasmine userContext 的属性(使用 TypeScript)

javascript - jasmine 2.0、requirejs、testr——只是一个没有错误的空白页面

angular - switchMap 使用 Angular http 客户端保留/取消请求

javascript - Angular Ngrx : Getting & displaying list of options from Java API

angular - 将参数附加到 Observable 中的嵌套数组

c# - 有效地使用单元测试/有人尝试过汇编方法吗?

java - 如何验证父类的 super.method() 的调用?