'React redux toolkit testing with jest, how to dispatch asyncthunk and the state?
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();
});
});
Solution 1:[1]
Can you include your error message?
I think you're almost there. Since you're rendering an actual component and redux store, you're actually doing an integration-style test. My guess is that your dispatch to getProducts()
is firing correctly, but the state isn't updating in your test because you haven't mocked an API response. See how msw
is being used to do this in the Redux Testing doc
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ty Hitzeman |