我是redux-toolkit及其测试的新手。我正在尝试为createAsyncThunk
调用 API 并通过 API 中的数据更新状态的 a 编写测试。我的异步 thunk 被我的组件中的一个按钮调用,而不是测试 thunk 本身,我正在我的组件中测试它的实现。我正在使用Mock Service Worker库来模拟我的 API 调用。以下是我测试失败的截图
这是我正在运行的测试
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");
});
我createAsyncThunk
的也很简单
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"];
}
);