reduxjs / redux-mock-store

A mock store for testing Redux async action creators and middleware.
MIT License
2.5k stars 148 forks source link

Issue with Store Helpers #174

Open satheshrgs opened 4 years ago

satheshrgs commented 4 years ago

I have a scenario in which a method uses Store Helper to get State. When I try to test the function using the mock store which I have created, it uses the original store instance ( since it is in a helper file).

code.js

export const testFunction() {
const res = getValueFromHelper();
console.log(res);
}

helper.js

export const getValueFromHelper = () => store.getState.SomeReducer;

code.test.js

const store = mockStore({ SomeReducer:{} })
console.log(store.getState().SomeReducer);  // Here value is correct
testFunction(); // But here it returning original state value
dmitry-zaets commented 4 years ago

Probably you have a typo here:

export const getValueFromHelper = () => store.getState.SomeReducer;

should be

export const getValueFromHelper = () => store.getState().SomeReducer;

Also you are referring to the global variable called store in your getValueFromHelper function.

So here you have 2 options.

  1. Assign a mocked store into this variable.
  2. Avoid using a global state variable and pass the store as a parameter to the function (preferred, to avoid dependencies)

helper.js

export const getValueFromHelper = (store) => store.getState.SomeReducer;

code.test.js

const store = mockStore({ SomeReducer:{} })
console.log(store.getState().SomeReducer);  // Here value is correct
testFunction(store); // But here it returning original state value

code.js

export const testFunction(state) {
  const res = getValueFromHelper(state);
  console.log(res);
}