我正在使用 ngxs 进行角度状态处理,并且我正在尝试将我们的组件作为单元进行测试,因此最好只使用模拟商店、状态等。
我们在组件中的内容类似于:
export class SelectPlatformComponent {
@Select(PlatformListState) platformList$: Observable<PlatformListStateModel>;
constructor(private store: Store, private fb: FormBuilder) {
this.createForm();
this.selectPlatform();
}
createForm() {
this.selectPlatformForm = this.fb.group({
platform: null,
});
}
selectPlatform() {
const platformControl = this.selectPlatformForm.get('platform');
platformControl.valueChanges.forEach(
(value: Platform) => {
console.log("select platform " + value);
this.store.dispatch(new PlatformSelected(value));
}
);
}
}
我们的夹具设置看起来像这样,所以我们可以检查商店的调用:
describe('SelectPlatformComponent', () => {
let component: SelectPlatformComponent;
let fixture: ComponentFixture<SelectPlatformComponent>;
let store: Store;
beforeEach(async(() => {
const storeSpy = jasmine.createSpyObj('Store', ['dispatch']);
TestBed.configureTestingModule({
imports: [ReactiveFormsModule],
declarations: [SelectPlatformComponent],
providers: [{provide: Store, useValue: storeSpy}]
})
.compileComponents();
store = TestBed.get(Store);
}));
但是当我们运行它时,我们得到以下错误:
Error: SelectFactory not connected to store!
at SelectPlatformComponent.createSelect (webpack:///./node_modules/@ngxs/store/fesm5/ngxs-store.js?:1123:23)
at SelectPlatformComponent.get [as platformList$] (webpack:///./node_modules/@ngxs/store/fesm5/ngxs-store.js?:1150:89)
at Object.eval [as updateDirectives] (ng:///DynamicTestModule/SelectPlatformComponent.ngfactory.js:78:87)
at Object.debugUpdateDirectives [as updateDirectives] (webpack:///./node_modules/@angular/core/fesm5/core.js?:11028:21)
at checkAndUpdateView (webpack:///./node_modules/@angular/core/fesm5/core.js?:10425:14)
at callViewAction (webpack:///./node_modules/@angular/core/fesm5/core.js?:10666:21)
at execComponentViewsAction (webpack:///./node_modules/@angular/core/fesm5/core.js?:10608:13)
at checkAndUpdateView (webpack:///./node_modules/@angular/core/fesm5/core.js?:10431:5)
at callWithDebugContext (webpack:///./node_modules/@angular/core/fesm5/core.js?:11318:25)
at Object.debugCheckAndUpdateView [as checkAndUpdateView] (webpack:///./node_modules/@angular/core/fesm5/core.js?:10996:12)
我可以为此启用整个 ngxs 模块,但随后我需要创建服务模拟以注入状态对象,我不喜欢这样,因为我不再单独测试组件。我试图创建一个模拟 SelectFactory,但它似乎没有从模块中导出。
有没有办法模拟 SelectFactory,或者直接将一些模拟注入到 platformList$ 中?其他建议?