NGRX:单元测试如何模拟两个不同的选择器



>我一直在尝试在组件中添加模拟存储,但是遇到了一个问题,即在MockStore类中返回我的选择方法只能返回1种类型。 但是我需要能够返回其中任何一个。

这是我的设置

test.spec.ts

class MockStore {
public select(obj: any): any {
return of(fruit)
}
}
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
FormsModule
],
providers: [
{ provide: Store, useClass: MockStore }
]
}).compileComponents()
}))

组件.ts

ngOnInit(): void {
this.fruit = this.store.select(fruitList)
this.animal = this.store.select(allAnimals)
}
init(): void {
const reptile = this.animal.subscribe(animal => {
animal.filter(a => a.type === 'coldBlood')
})
}

水果选择器.ts

// Using NRGX entity pattern
export const selectFruitState = (state): FruitState => state.allFruits
export const fruitList = createSelector(selectFruitState, selectAll)

动物选择器.ts

// using normal create selector pattern
export const selectAnimalState = (state): AnimalState => state.zoo.land
export const allAnimals = createSelector(selectAnimalState, status => status.allAnimals)

所以问题是我的两个商店都有不同的数据结构

// Fruit data structure
export const fruit = {
sweet: sweet.reducer,
salty: salty.reducer,
bitter: bitter.reducer
}
// Animal data structure
{
id: [1, 2, 3],
enitity: ['monkey', 'elephant', 'snake']
}

更改数据结构会有问题,因为我在其他方面也有不同的结构,我已经尝试像这样将动物数据添加到 MockStore

class MockStore {
public select(obj: any): any {
fruit['animal'] = animal.reducer
return of(fruit)
}
}

但是这种方法的问题是我在 init(( 方法中有一个 animal.filter(( 它试图访问对象 这将导致错误。我不想仅仅因为单元测试而更改我的数据结构

将模拟商店与 mckselectors 结合使用 - https://ngrx.io/guide/store/testing#using-mock-selectors

providers: [
provideMockStore({
selectors: [
{ selector: fromBooks.getSearchQuery, value: '' },
{ selector: fromBooks.getSearchResults, value: [] },
{ selector: fromBooks.getSearchLoading, value: false },
{ selector: fromBooks.getSearchError, value: '' },
],
}),

可以在示例应用程序中找到更多示例

最新更新