首页 > 解决方案 > Angular6 ngrx:无法读取未定义的属性“ID”

问题描述

我正在尝试做一个简单的选择器测试。但是,测试没有通过并给我以下错误:“无法读取未定义的属性 '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();

标签: angulartypescriptunit-testingngrx

解决方案


您必须将您的状态包装在根状态中,因为您还在后台使用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']
 }
};

另一种选择是使用文档projector中解释的功能。

更多示例可以在我如何测试我的 NgRx 选择器中找到


推荐阅读