问题
I want to assert that when a function gets my redux state value using store.getState()
, it does various things based on the conditions of that state. How am I able to assert / mock what I want the state value to be for certain tests using the store.getState()
method? Thanks.
sampleFunction.js:
import { store } from './reduxStore';
const sampleFunction = () => {
const state = store.getState();
let result = false;
if (state.foo.isGood) {
result = true;
}
return result;
};
export default sampleFunction;
sampleFunction.test.js:
import sampleFunction from './sampleFunction.js';
test('sampleFunction returns true', () => {
// assert that state.foo.isGood = true
expect(sampleFunction()).toBeTruthy();
});
回答1:
What you can do to mock your store is
import { store } from './reduxStore';
import sampleFunction from './sampleFunction.js';
jest.mock('./reduxStore')
const mockState = {
foo: { isGood: true }
}
// in this point store.getState is going to be mocked
store.getState = () => mockState
test('sampleFunction returns true', () => {
// assert that state.foo.isGood = true
expect(sampleFunction()).toBeTruthy();
});
来源:https://stackoverflow.com/questions/56399446/mocking-store-getstate