我正在使用ngrx(用于Redux逻辑)和rxjs(用于observable)处理angular 2项目。
现在我尝试通过运行自动创建的.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();
});
});
我照看问题,错误是:
没有商店提供商
所以我补充说:(我用茉莉花进行测试)
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ],
providers: [Store]
})
.compileComponents();
}));
现在我还有其他错误:
没有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)
我该怎么办?
答案 0 :(得分:3)
您应该创建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)}
]
...
})