我正在使用 ngrx 存储进行状态管理,并为使用工厂选择器的组件编写测试用例,在测试用例中我需要传递模拟数据
客户.selector.ts
export const selectCustomer = (id: string) =>
createSelector(selectCustomers, (customers) => customers[id]);
客户.组件.ts
const data = this.store.select(selectCustomer(3));
问题是没有提供用于模拟工厂选择器的文档。所以我可以测试一下
您是否尝试过使用
MockStore
中的'@ngrx/store/testing'
?
这里回答了一个类似的问题:如何在组件中模拟 ngrx 选择器
他们的解决方案:
imports { ... } from '...';
import { MockStore, provideMockStore } from '@ngrx/store/testing';
describe('MyComponent', () => {
let store: MockStore<AppState>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ MyComponent ],
imports: [
...
],
providers: [
...
provideMockStore({initialState}),
],
schemas: [NO_ERRORS_SCHEMA],
})
.compileComponents();
fixture = TestBed.createComponent(MyComponent);
store = TestBed.inject(MockStore);
component = fixture.componentInstance;
store.overrideSelector(mySelector, {
id: 0,
name: 'test',
value: 50,
})
fixture.detectChanges();
spyOn(store, 'dispatch').and.callFake(() => {});
});
});
官方文档:https://ngrx.io/guide/store/testing#using-mock-selectors