Answer the question
In order to leave comments, you need to log in
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;
}
};
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 questionAsk a Question
731 491 924 answers to any question