我正在从事 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/