Angular6 ngrx: Cannot read property 'ids' of undefined

Viewed 7530

I'm trying to do a simple selector test. However, the test does not pass and gives me the following error: "Cannot read property 'ids' of undefined". In app works correctly, but when selectCustomers is called, it returns undefined.

Test

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);
    });
});

The selector code is the following:

export const selectCustomer = createFeatureSelector<CustomerState>('customer');

export const selectCustomers = createSelector(
    selectCustomer,
    fromCustomer.selectAll
);

The reducer:

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();
1 Answers

You have to wrap your state inside a root state because you're also using the selectCustomer selector under the hood.

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']
 }
};

Another option is to use the projector function as explained in the docs.

More examples could be found in How I test my NgRx selectors

Related