I want to write unit test which checks if data (onLoad) from dispatching async thunk is delivered into state.
It's first time when i'm writing unit tests and it's black magic for me.
My solution it's not working because my state is always empty object.
My component has following logic:
useEffect(() => {
dispatch(getProducts({ filters: false }));
}, [dispatch, filters]);
Here is what i've tried:
import {
render as rtlRender,
screen,
fireEvent,
cleanup,
} from "@testing-library/react";
import { Provider } from "react-redux";
import { store as myStore } from "store/root-reducer";
import ProductList from "components/product/product-list/product-list";
import { productSlice } from "store/slices/product/product.slice";
describe("Product components", () => {
const renderWithRedux = (component) =>
rtlRender(<Provider store={myStore}>{component}</Provider>);
const thunk =
({ dispatch, getState }) =>
(next) =>
(action) => {
if (typeof action === "function") {
return action(dispatch, getState);
}
return next(action);
};
const create = () => {
const store = {
getState: jest.fn(() => ({})),
dispatch: jest.fn(),
};
const next = jest.fn();
const invoke = (action) => thunk(store)(next)(action);
return { store, next, invoke };
};
const initialState = {
product: null,
products: [],
errorMessage: "",
isFetching: false,
filters: false,
};
it("should render product list after dispatching", async () => {
renderWithRedux(<ProductList />);
const { store, invoke } = create();
invoke((dispatch, getState) => {
dispatch("getProducts"); // i want to dispatch asyncthunk which is called getProducts()
getState();
});
expect(store.dispatch).toHaveBeenCalledWith("getProducts");
expect(store.getState).toHaveBeenCalled();
});
});