flo*_*olu 3 typescript ngrx angular ngrx-store angular-test
我的 NgRx 实现有一个智能组件测试,如下所示:
describe( 'Component', () => {
let store: MockStore<State>;
beforeEach( async( () => {
TestBed.configureTestingModule( {
/* ... */
providers: [
provideMockStore( { initialState: fromReducer.initialState } )
]
} ).compileComponents();
store = TestBed.get<Store<State>>( Store );
} ) );
it( 'should load items in #ngOnInit', () => {
store.setState( {
item: {
...fromReducer.initialState,
entities: { [item.id]: item },
},
otherFeature: null,
otherFeature: null,
otherFeature: null
} );
component.items$.subscribe( items =>
store.select( ItemStoreSelectors.selectItems ).subscribe( fromStore => expect( items ).toEqual( fromStore ) )
);
} );
});
Run Code Online (Sandbox Code Playgroud)
我使用provideMockStore和setState来模拟我的 NgRx 状态。这样一切正常,但我真的不喜欢它的这一部分:
store.setState( {
item: {
...fromReducer.initialState,
entities: { [item.id]: item },
},
otherFeature: null,
otherFeature: null,
otherFeature: null
} );
Run Code Online (Sandbox Code Playgroud)
我必须将我的状态的所有其他特征切片添加到setState函数中。否则 Typescript 会抛出错误。
所以最好我不想设置根状态,而是像这样的特定功能切片:
store.setState( {
...fromReducer.initialState,
entities: { [item.id]: item },
} );
Run Code Online (Sandbox Code Playgroud)
我provideMockStore在此处找不到有关如何用于特定状态切片的任何文档。
我建议在这里采取不同的方法。你应该做的是独立地对你的选择器和组件进行单元测试。
NgRx 8 允许模拟选择器。在您的组件中使用它来验证组件的逻辑是否正确。
然后,单独对您的选择器进行单元测试,以验证您的选择器是否按预期工作。
通过这种方式,测试是独立的,而不是脆弱的,并且是真正的单元测试。
编辑:我链接的文档是官方的,但是模拟选择器的另一种方法是:
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideMockStore({
selectors: [
{
selector: yourSelectorNameHere,
value: someMockValueHere
}
]
})
]
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6190 次 |
| 最近记录: |