I am new to the redux-toolkit and its testing. I am trying to write a test for a createAsyncThunk
that calls an API and updates the state by the data from the API. My async thunk is being called by a button in my component and rather than testing the thunk itself, I am testing its implementation in my component. I am using the Mock Service Worker library to mock my API calls. Following is the screenshot of my failed test
Here is the test that I am running
import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import { rest } from "msw";
import { setupServer } from "msw/node";
import App from "./App";
import { Provider } from "react-redux";
import { createStore } from "./redux/store";
const server = setupServer(
rest.get("/api", (req, res, ctx) => {
return res(ctx.json("10"), ctx.delay(150));
})
);
beforeAll(() => server.listen());
afterEach(() => server.restoreHandlers());
afterAll(() => server.close());
const MockApp: React.FunctionComponent = () => {
return (
<Provider store={createStore()}>
<App />
</Provider>
);
};
it("Should simulate the api call", async () => {
render(<MockApp />);
const apiButton = screen.getByText("Api call");
const counter = await screen.findByTestId("displayCount");
fireEvent.click(apiButton);
expect(counter).toHaveTextContent("10");
});
My createAsyncThunk
is quite simple as well
export const fetchUserById = createAsyncThunk(
"users/fetchById",
// Declare the type your function argument here:
async (userId: number) => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${userId}`
);
// Inferred return type: Promise<MyData>
const res = await response.json();
return res.userId as MyData["userId"];
}
);