How to write Unit Test in Jest For React and Redux-Store
While writing the unit test in jest (testing-library/react)
I faced the issue related to redux store i.e. how to pretend that fake store values. And due to this my all test cases were getting failed as well as not able to get the coverage report. To resolve the issue we need to add configuration related to store as in the code block.
import { render, screen, fireEvent, within } from "@testing-library/react";
import {BrowserRouter as Router} from 'react-router-dom';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk'
import configureStore from 'redux-mock-store';
import TVSSalesSheet from "./TVSSalesSheet";
describe('React Test Inside <TVSSalesSheet />', () => {
const initialState = {
Sales: {
liabilitiesData: [
{
"year": 2023,
"amountPayables": 500,
"loan": 0
},
{
"year": 2022,
"amountPayables": 1000,
"loan": 0
},
{
"year": 2021,
"amountPayables": 0,
"loan": 0
},
{
"year": 2020,
"amountPayables": 0,
"loan": 0
},
{
"year": 2019,
"amountPayables": 0,
"loan": 0
}
]
};
const middlewares = [thunk]
const mockStore = configureStore(middlewares);
let store;
test('Check if Sales field exists or not', () => {
store = mockStore(initialState);
render(<Provider store={store}>
<Router>
<TVSSalesSheet />
</Router>
</Provider>);
const textElement = screen.getByText(/Sales/i);
expect(textElement).toBeInTheDocument();
});
})
Thank you for going through the article. If you are looking for any freelancer developer related to React, React Native, Node.js, GraphQl. Please let me know. I will be glad to help you.
To tell us about your requirement please fill the form: https://docs.google.com/forms/d/1uh343ab8uwVhCpozi_etFyV67f6zVoIiMlrYKLwOgnE/prefill