Search code examples
reduxexpectcreate-react-appreselect

How to test a Reselect selector from nested reducer?


I created a simple Redux selector with the Reselect library. The selector gets the last object in an array.

In the Reselect docs, the testing example is built with Assert library rather than Expect library, but my app originates from React Create App so I have Expect and Jest included.

Anyway, regardless of how I write the selector test, it gets hung up on nested reducer: TypeError: Cannot read property 'arrayOfObj' of undefined.

Selectors.js

import { createSelector } from 'reselect'

const getArrayOfObj = (state) => state.reducer1.arrayOfObj

export const getLastObj = createSelector(
  [ getArrayOfObj ],
  (arrayOfObj) => {
    return arrayOfObj[arrayOfObj.length-1]
  }
)

Selectors.test.js

import * as selectors from 'Selectors'

const mockState = {
    reducer1: {
        arrayOfObj: [
        {id: 1}, 
        {id: 2}, 
        {id: 3}, 
        {id: 4},
      ],
      ...
    },
    reducer2: {
      ...
    }
}

describe('selectors', () => {
  it('getLastObj should get last obj in array', () => {
    expect(selectors.getLastObj(mockState)).toDeepEqual({id: 4});
  });
});

Solution

  • I was able to resolve the error by changing the expect statement from .toDeepEqual() to .toEqual()