I
I
Ivan Ivanov2020-03-28 08:45:52
Test Driven Development
Ivan Ivanov, 2020-03-28 08:45:52

How to write a unit test for a reducer function?

I am new to unit testing. I have a problem, I need to write a test that would test the reducer. I wrote something myself, but due to the fact that I use localStorage in initialState, the test does not work for me. The error sounds something like this: TypeError: localStorage.getItem is not a function. I ask you to help me write this test.

My reducer:

import actionTypes from "...";
import en from '...'
import ru from '...'

const translates = {en, ru};

export const getLanguage = () => {
    const currentLocale = localStorage.getItem('language');
    return translates[currentLocale ? currentLocale : 'en'];
};

const initialState = {
    dictionary: getLanguage(),
};

export const localeReducer = (state = initialState, action) => {
    switch (action.type) {
        case actionTypes.SET_LOCALE: return {...state, dictionary: translates[action.payload]};
        default:
            return state;
    }
};


My test that doesn't work:

import {localeReducer} from '...'
import actionTypes from "...";
import en from '...'
import ru from '...'

describe('testing localeReducer', () => {
    it('testing localeReducer with action {type: actionTypes.SET_LOCALE}', () => {
        console.log("initialState");
        const translates = {en, ru};
        const initialState = {
            dictionary: translates['ru'],
        };
        let expectedInitialState = {
            dictionary: translates['en'],
        };
        const actionCreator = { type: actionTypes.SET_LOCALE, payload: 'en' };
        const actualInitialState = localeReducer(initialState, actionCreator);
        assert.deepEqual(actualInitialState, expectedInitialState);
    });
});

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question