Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write tests ( Jest + Enzyme ) for extraReducers of createSlice ()?

I have started to create my application using @reduxjs/toolkit and kind of got stuck. I find no resource anywhere which can guide me with how to unit tests the logic in extraReducers. Any help would be appreciable.

Example:

Example:

const fetchList = createAsyncThunk('example/fetchList', async ({skip, reset, ...rest}) => {
  const request = {
    skip: reset ? initialState.skip : skip,
    ...rest,
  };
  return await getList(request);
});
const exampleSlice = createSlice({
  name: 'example',
  initialState: {id: '', list: []},
  reducers: {
    resetParams() {
      return {id: '', list: []}
    },
    setId(state, {payload}) {
      state.id = payload.id
    }
  },
  extraReducers: {
    [fetchList.pending]: (state) => {
      state.fetching = true;
    },
    [fetchList.fulfilled]: (state, {payload = []}) => {
      return {
        fetching: false,
        id: state.id + 1,
        list: payload
      }
    },
    [fetchList.rejected]: (state, {error}) => {
      state.fetching = false;
    },
  },
});

//Tests .. for setId()

const initialState = {
  id: 1,
  list : []
}
const result = exampleSlice.reducer(initialState, exampleSlice.actions.setId({id: 10}))
expect(result.id).toEqual(10)

How can I test logic in extraReducers for fetchList.fulfilled and fetchList.rejected!

like image 916
Anand Garg Avatar asked Jun 22 '20 16:06

Anand Garg


1 Answers

You can test it the same way as what you've shown.

Here's a simple way to just test the logic of the reducer based on the action types that createAsyncThunk outputs.

import reducer, {
  fetchList
} from './exampleSlice';

describe('exampleSlice', () => {
  describe('reducers', () => {
    const initialState = { id: '', list: [], fetching: false }
    
    it('sets fetching true when fetchList is pending', () => {
      const action = { type: fetchList.pending.type };
      const state = reducer(initialState, action);
      expect(state).toEqual({ id: '', list: [], fetching: true });
    });

    it('sets the id and list when fetchList is fulfilled', () => {
      const action = { type: fetchList.fulfilled.type, payload: { id: 1, list: [2, 3]} };
      const state = reducer(initialState, action);
      expect(state).toEqual({ id: 1, list: [2, 3], fetching: false });
    });

    it('sets fetching false when fetchList is rejected', () => {
        const action = { type: fetchList.rejected.type, payload: { error: 'some error' } };
        const state = reducer(initialState, action);
        expect(state).toEqual({ id: '', list: [], fetching: false });
      });
  });

});

I also threw up a simple example of the same concept on a demo CSB: https://codesandbox.io/s/rtk-14-addmatcher-counter-test-l11mt?file=/src/features/counter/counterSlice.test.ts

like image 141
Matt Sutkowski Avatar answered Sep 23 '22 17:09

Matt Sutkowski