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();
});
A mock store for testing Redux async action creators and middleware. The mock store will create an array of dispatched actions which serve as an action log for tests. Please note that this library is designed to test the action-related logic, not the reducer-related one.
Redux can be tested with any test runner, since it's just plain JavaScript. One common option is Jest, a widely used test runner that comes with Create-React-App, and is used by the Redux library repos. If you're using Vite to build your project, you may be using Vitest as your test runner.
Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new , and allowing test-time configuration of return values.
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();
});
import { store } from './reduxStore';
import sampleFunction from './sampleFunction.js';
beforeAll(() => {
jest.mock('./reduxStore')
const mockState = {
foo: { isGood: true }
}
// making getState as mock function and returning mock value
store.getState = jest.fn().mockReturnValue(mockState)
});
afterAll(() => {
jest.clearAllMocks();
jest.resetAllMocks();
});
test('sampleFunction returns true', () => {
// assert that state.foo.isGood = true
expect(sampleFunction()).toBeTruthy();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With