我正在学习使用 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();;
所以我希望在运行此单元测试时,我应该在组件 .ts 文件中输入订阅(“此处的一些逻辑”部分)并且 res
将等于 {a: 'b', c: 'd'}
.
这不会发生,而是忽略模拟的选择器并使用真实的选择器。
我尝试过的事情:
store.overrideSelector(someSelector('param'), {a: 'b', c: 'd')
将
fixture.detectChanges()
、await fixture.whenStable()
放在不同的地方
现在我别无选择,NGRX documentation几乎没有涵盖任何内容。
最佳答案
模拟选择器似乎不是最好的解决方案。 最好模拟商店本身。
您可以提供以下状态:
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.
})
}
关于angular - 如何在 nrgx 8 单元测试中模拟选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58787505/