How does one unit test Redux set up with Redux Tool Kit's 'createSlice'?

Viewed 7060

I'm looking into how to unit test the Redux code for our project using Jest. I've been reading through the 'official' Redux recommendations, but our code differs from the Redux setup they're referencing since we used the Redux Tool Kit (RTK) and 'createSlice', which automates some of the process, such as action creator creation. How do we unit test the Redux created by the RTK and createSlice? Since, for instance, the action creators are created automatically, does testing them make any sense? In general, since much of the RTK setup is automatic, what do we need to test? Does the Redux Tool Kit have any tools to make this easier? (I do not see any).

In addition, we also have Redux Thunks, which we've set up 'by hand'. We see what the Redux documentation recommends, but with reference to the above, should we handle this testing differently since we set up the main Redux using the RTK and createSlice?

Finally, the API calls on which the Redux depends run through Apollo Client. I see Apollo´s recommendations on how to test React with the React client. To test Redux, should we mock the Apollo Client using something like https://www.npmjs.com/package/mock-apollo-client ?

2 Answers

There's never been any real benefit in testing plain action creators yourself. Verifying that addTodo("buy milk") returns {type: "todos/addTodo", payload: "buy milk"} does not give me any real confidence that my app is behaving correctly.

Testing reducers is the same as it's always been: const actual = reducer(testState, someAction), and expect(actual).toEqual(expected).

Testing thunks may or may not be of actual benefit. In particular, if you're using RTK's createAsyncThunk API, there probably isn't much point to testing those since the majority of the logic is from RTK itself.

(Note that there's an open PR to rework that Redux testing docs page.)

You can import the actions into your test file just like you import inside your component.

import { setApiInProgress } from '../src/blom/redux/api/apislice'

describe('actions', () => {
    it('should create an action to add a todo', () => {
      const payload = false
      const expectedAction = {
        type: 'api/setApiInProgress',
        payload
      }
      expect(setApiInProgress(true)).toEqual(expectedAction)
    })
})
Related