代码之家  ›  专栏  ›  技术社区  ›  serp002

在使用React Query+Axios模拟适配器进行测试时,如何提高错误响应速度?

  •  0
  • serp002  · 技术社区  · 4 年前

    我正在为一个组件编写测试,该组件使用React Query with Jest、React测试库和Axios模拟适配器(所有请求都通过Axios发送)

    我想确保axios返回500错误时出现错误消息,我的测试完成了这一点- 但问题是,实际出现错误大约需要8秒钟

    以下是测试:

      it("should show error message when bad request returned", async () => {
        mock.onGet("/url-example").reply(500);
    
        renderWithProvider(
            <TestContactUsComponent/>
        );
    
        expect(screen.getByTitle(/loading spinner/i)).toBeInTheDocument();
    
        await waitForElementToBeRemoved(
          () => screen.getByTitle(/loading spinner/i),
          { timeout: 10000 }
       );
    
        await expect(screen.queryByTestId("simple-error")).toBeInTheDocument();
    }, 10000);
    

    我从useQuery中记录了状态,然后返回 loading 大约7-8秒,然后最终返回错误,移除微调器并呈现错误消息。

    有没有办法减少这项工作所需的时间?来自axios mock adapter的200个请求的测试几乎立即完成,因此不确定为什么500个错误场景需要这么长时间。

    就组件的正常行为而言,它会在大约一秒钟内呈现错误消息,因此我认为这不是组件本身的问题。

    0 回复  |  直到 4 年前
        1
  •  0
  •   TkDodo    4 年前

    默认情况下,react query会进行3次重试,并进行指数退避。建议通过 QueryClientProvider -这是在 the official docs here .我想你会想从内心开始 renderWithProvider .

     const queryClient = new QueryClient({
       defaultOptions: {
         queries: {
           // ✅ turns retries off
           retry: false,
         },
       },
     })
     const wrapper = ({ children }) => (
       <QueryClientProvider client={queryClient}>
         {children}
       </QueryClientProvider>
     );