[英]How do I mock selectors in nrgx 8 unit tests?
我正在学习使用 Jest 为 ngrx8 应用程序编写单元测试。
我正在测试一个订阅了 ngOnInit 中选择器的组件:
ngOnInit(): void {
this.store.pipe(select(someSelector(this.parameter))).subscribe((res:
// some logic here
});
}
在 .spec.ts 文件中,我将provideMockStore
放在 TestBed 配置中:
TestBed.configureTestingModule({
// ...
providers: [
provideMockStore({
initialState, // defined somewhere above
selectors: [
{
selector: someSelector('param'),
value: {a: 'b', c: 'd'}
}
]
})
]
// ...
}).compileComponents();;
所以我希望在运行这个单元测试时,我应该在 component.ts 文件中输入订阅(“这里的一些逻辑”部分),并且res
将等于{a: 'b', c: 'd'}
。
这不会发生,而是忽略模拟选择器并使用真实的选择器。
我尝试过的事情:
store.overrideSelector(someSelector('param'), {a: 'b', c: 'd')
将fixture.detectChanges()
和await fixture.whenStable()
放在不同的地方
现在我别无选择, NGRX 文档几乎没有涵盖任何内容。
Mocking 选择器似乎不是最好的解决方案。 最好模拟商店本身。
您可以在以下位置提供 state:
provideMockStore({ initialState: your_state })
或者
mockStore.setState(your_state);
mockStore.setState(...)
允许您在测试中的商店中使用不同的值进行测试。
但如果您有一家复杂的商店,我建议您执行以下操作:
MockStoreState
。
type RecursivePartial<T> = {
[P in keyof T]?:
T[P] extends (infer U)[] ? RecursivePartial<U>[] :
T[P] extends object ? RecursivePartial<T[P]> :
T[P];
};
export class MockStoreState {
private store_a: RecursivePartial<Store_A>;
private store_b: RecursivePartial<Store_b>;
build(): any {
const defaultStore_a = {
...
};
const defaultStore_b = {
...
};
return {
store_a: { ...defaultStore_a , ...this.store_a},
store_b: { ...defaultStore_b , ...this.store_b },
};
}
setStore_a(value: RecursivePartial<Store_A>): Store_A_State {
this.store_a= value;
return this;
}
setStore_b(value: RecursivePartial<DatasourceState>): Store_B_State {
this.store_b= value;
return this;
}
}
describe(MyComponent.name, () => {
...
let mockStore: MockStore<any>;
beforeEach(() => {
...
mockStore = TestBed.get(Store);
})
it('...', () => {
const state = new MockStoreState().setStore_a({...})
.build();
mockStore.setState(state);
// HERE you have set the data in your store.
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.