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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With