Testing

Тестування Reducers

Тестування редюсерів — це найпростіша частина. Вам просто потрібно викликати функцію з певним станом і дією, і перевірити результат.

Тестування Reducers

Тестування редюсерів — це найпростіша частина. Вам просто потрібно викликати функцію з певним станом і дією, і перевірити результат.

Приклад Reducer

features/counter/counterSlice.js
import { createSlice } from '@reduxjs/toolkit';

export const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment: (state) => { state.value += 1; },
    decrement: (state) => { state.value -= 1; },
    incrementByAmount: (state, action) => { state.value += action.payload; },
  },
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;

Написання тесту

features/counter/counterSlice.test.js
import reducer, { increment, decrement, incrementByAmount } from './counterSlice';

describe('counter reducer', () => {
  const initialState = { value: 0 };

  it('should handle initial state', () => {
    // Передаємо undefined як state і порожній action
    expect(reducer(undefined, { type: 'unknown' })).toEqual({
      value: 0,
    });
  });

  it('should handle increment', () => {
    const actual = reducer(initialState, increment());
    expect(actual.value).toEqual(1);
  });

  it('should handle decrement', () => {
    const actual = reducer(initialState, decrement());
    expect(actual.value).toEqual(-1);
  });

  it('should handle incrementByAmount', () => {
    const actual = reducer(initialState, incrementByAmount(2));
    expect(actual.value).toEqual(2);
  });
});
Навіть якщо ви використовуєте Redux Toolkit, редюсер — це все одно чиста функція. Вам не потрібно мокати Store для цих тестів.

👉 Далі: Тестування Селекторів

Copyright © 2026