我不知道如何为 Angular 中的独立组件测试导入/提供模拟商店。为非独立组件测试提供模拟商店是通过
provideMockStore()
完成的,但这似乎不适用于独立组件。
@Component({
standalone: true,
imports: [
CommonModule,
FeatureStoreModule, // Import feature store module to access selectors/actions
],
selector: 'standalone',
templateUrl: './standalone.component.html',
styleUrls: ['./standalone.component.scss'],
})
export class StandaloneComponent {
constructor(private store: Store) {}
dispatchAction(): void {
this.store.dispatch(featureStoreAction()); // Dispatch action imported from FeatureStoreModule
}
}
describe('StandaloneComponent', () => {
let component: StandaloneComponent;
let fixture: ComponentFixture<StandaloneComponent>;
let store: MockStore;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [StandaloneComponent],
providers: [provideMockStore()], // Provide a mocked store for component
}).compileComponents();
store = TestBed.inject(MockStore);
fixture = TestBed.createComponent(StandaloneComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
"@angular/core": "16.2.4",
"@ngrx/effects": "16.0.1",
"@ngrx/entity": "16.0.1",
"@ngrx/router-store": "16.0.1",
"@ngrx/store": "16.0.1",
"jest": "29.4.3",
"jest-preset-angular": "13.1.1",
运行此测试会引发错误:
NullInjectorError: NullInjectorError: No provider for _StoreRootModule!
最有可能的是,对于用于测试的独立组件,我们必须利用
overrideComponent
。
你可以尝试以下方法看看它是否有效(用!!来评论)?
describe('StandaloneComponent', () => {
let component: StandaloneComponent;
let fixture: ComponentFixture<StandaloneComponent>;
let store: MockStore;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [StandaloneComponent],
providers: [provideMockStore()], // Provide a mocked store for component
})
// !! Add overrideComponent here
.overrideComponent({
// !! set the providers.
set: {
providers: [provideMockStore()]
},
// !! Remove the feature store module
remove: {
imports: [FeatureStoreModule]
}
})
.compileComponents();
// !! Not sure if the below line will work.
// store = TestBed.inject(MockStore);
// !! Try getting the store like this, from the component first
// before going to the root injector
store = fixture.debugElement.injector.get(MockStore);
fixture = TestBed.createComponent(StandaloneComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});