Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Intermediate

Testing Slices

Definition

The practice of writing unit tests for RTK slices (which encompasses testing the initial state and the reducers).

Explain Like I'm New

Because reducers are 'Pure Functions', they are the easiest thing in the world to test. You don't need a browser or a fake DOM. You just call the reducer function, hand it a fake state and a fake action, and assert that the output matches what you expect.

Real World Example

Using Jest or Vitest to test that dispatching `increment()` changes the state from `0` to `1`.

Common Use Cases

  • •Unit testing core business logic

Interactive Example

import counterReducer, { increment } from './counterSlice';

describe('counter reducer', () => {
  
  it('should handle initial state', () => {
    // Pass undefined state, expect the default initial state
    expect(counterReducer(undefined, { type: 'unknown' })).toEqual({ value: 0 });
  });

  it('should handle increment', () => {
    const startingState = { value: 5 };
    
    // Call the reducer directly with the starting state and the action
    const nextState = counterReducer(startingState, increment());
    
    // Verify the math works!
    expect(nextState.value).toEqual(6);
  });
});

Interview Questions

basic

  • Do you need to mock a full Redux Store just to test a reducer function?

intermediate

  • How do you test the initial state of a reducer?

Flash Cards

Question

Mock full store?

Click to reveal answer
Answer

No! A reducer is just a plain JavaScript function: `(state, action) => newState`. You can import it and call it directly in your test file.

Question

Test initial state?

Click to reveal answer
Answer

Call the reducer with `undefined` as the state, and an empty action `{ type: 'unknown' }`. It should return your defined `initialState`.