我正在尝试做一个简单的选择器测试。但是,测试没有通过,并给我以下错误:“无法读取未定义的属性'ids'”。在应用中正常运行,但是在调用selectCustomers
时,它返回未定义的值。
测试
fdescribe('Customer Selector', () => {
const customerState: fromQuoteCustomers.CustomerState = {
customersLoaded: true,
entities: {
'cus01': {
id: 'cus01',
web: 'web01',
cif: 'cif01',
currencyId: 'id-01',
telephone: 666616666,
name: 'name1',
email: 'example@mail.es'
},
'cus02': {
id: 'cus02',
web: 'web02',
cif: 'cif02',
currencyId: 'id-02',
telephone: 111000000,
name: 'name2',
email: 'mail@example.es'
}
},
ids: ['cus01', 'cus02']
};
it('select customers', () => {
expect(selectCustomers(customerState).length).toBe(2);
});
});
选择器代码如下:
export const selectCustomer = createFeatureSelector<CustomerState>('customer');
export const selectCustomers = createSelector(
selectCustomer,
fromCustomer.selectAll
);
减速器:
export const adapter: EntityAdapter<Customer> = createEntityAdapter<Customer>();
export const initialState: CustomerState = adapter.getInitialState({
customersLoaded: false,
});
export function reducer(state = initialState, action: CustomerActions): CustomerState {
if (action) {
switch (action.type) {
case CustomerActionTypes.LoadCustomers:
return adapter.addMany(action.payload.customerList, state);
default:
return state;
}
}
return state;
}
export const {
selectAll,
selectEntities,
selectIds,
selectTotal
} = adapter.getSelectors();
答案 0 :(得分:2)
您必须将状态包装在根状态中,因为您还需要使用selectCustomer
选择器。
const customerState = {
customer: {
customersLoaded: true,
entities: {
'cus01': {
id: 'cus01',
web: 'web01',
cif: 'cif01',
currencyId: 'id-01',
telephone: 666616666,
name: 'name1',
email: 'example@mail.es'
},
'cus02': {
id: 'cus02',
web: 'web02',
cif: 'cif02',
currencyId: 'id-02',
telephone: 111000000,
name: 'name2',
email: 'mail@example.es'
}
},
ids: ['cus01', 'cus02']
}
};
另一种选择是使用the docs中所述的projector
函数。
更多示例可以在How I test my NgRx selectors
中找到