这个错误通常是由于没有正确地设置TestingModule引起的。检查测试中是否正确导入了StoreModule和ReactiveFormsModule,以及是否正确初始化了TestBed。确保将需要的模块添加到imports数组中,并通过compileComponents函数编译组件。此外,还要检查组件中是否正确导入了Store类,是否正确声明了store属性。如果仍然存在问题,可以尝试在测试文件顶部添加以下代码:
import { select } from 'rxjs/operators';
import { StoreModule, Store } from '@ngrx/store';
describe('YourComponent', () => {
let fixture;
let component;
let store: Store;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [StoreModule.forRoot({})],
providers: [Store]
})
store = TestBed.inject(Store);
spyOn(store, 'select').and.returnValue(of('value'));
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should test select function', () => {
component.methodThatCallStoreSelect();
expect(store.select).toHaveBeenCalled();
});
});
这段代码将创建一个spyOn来模拟store.select函数返回的Observable。这可以防止在测试中使用真实的store.select函数。最后,在组件中调用store.select时,会调用我们创建的spy,从而避免了测试错误。