如何使用react测试库测试使用Redux Toolkit Query(Redux API)创建的API钩子的react组件

e37o9pze  于 11个月前  发布在  React
关注(0)|答案(1)|浏览(127)

我正在使用Redux工具箱查询从React组件进行API调用。现在功能运行得很好,但我正在努力使用react-testing库为组件编写单元测试用例

== Redux Toolkit Query API ==

const AssetInstancesAPI = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: 'http://localhost:3003',
    headers: genHeaders(token)
  }),
  reducerPath: 'AssetInstances',
  tagTypes: [`table-contents`],
  endpoints: (build) => ({
    getAssetsTableData: build.query<any, void>({
      query: (body) => ({
        url: '/assets/summary',
        method: 'get',
        data: body
      }),
      providesTags: [`table-contents`]
    })
  })
});

export const { useGetAssetsTableDataQuery } = AssetInstancesAPI;

个字符

l3zydbqr

l3zydbqr1#

你需要模拟你的API调用。使用像https://mswjs.io/这样的库。然后你会有这样的东西:

//handlers.ts

import { rest } from "msw";

export const handlers = [
    rest.get("/assets/summary", async (req, res, ctx) => {
        return res(
            ctx.status(200),
            ctx.json({
                MOCK_DATA,
            })
        );
    })
]

//browser.ts

export const worker = setupWorker(...handlers);

//server.ts
export const server = setupServer(...handlers);

//setup.ts
beforeAll(() =>
    server.listen({
        //do stuff
    })
);

afterAll(() => server.close());
...

//main.ts
if(USING_MOCK){
  import('./browser')
   .then(({worker}) => {
      worker.start();
   })
   .then(() => {
      root.render(<Main/>);
   });
} else {
  root.render(<Main/>);
}

字符串

相关问题