与useswr一起使用测试库

    科技2026-08-10  13

    useSWR makes developing performant and complex React applications a snap. In many cases, it can remove the need for a global state management solution like Redux or MobX.

    useSWR使开发高性能和复杂的React应用程序变得轻而易举。 在许多情况下,它可以消除对Redux或MobX等全局状态管理解决方案的需求。

    We previously covered useSWR on Frontend Digest, but this time we want to take a deeper dive into using useSWR with React Testing Library.

    我们先前在Frontend Digest上介绍过useSWR ,但是这次我们想更深入地useSWR将React和React一起使用。

    One of my favourites things about SWR is it’s caching solution. However, this global caching system doesn’t play nicely with testing. We don’t want to leak state between tests. When we are testing our React applications, we want clean and predictable results.

    关于SWR,我最喜欢的事情之一是它的缓存解决方案。 但是,此全局缓存系统在测试中不能很好地发挥作用。 我们不想在测试之间泄漏状态。 在测试React应用程序时,我们希望获得干净且可预测的结果。

    In order to use SWR together with Testing Library, we need to clear this cache between each test run. We can do this in our setupTests file.

    为了与测试库一起使用SWR,我们需要在每次测试运行之间清除此缓存。 我们可以在setupTests文件中执行此操作。

    We point to this file from our setupFilesAfterEnv configuration. To learn more about the ins and outs of Jest configuration, check out their documentation here.

    我们从setupFilesAfterEnv指向此文件 配置。 要了解有关Jest配置的详细信息,请在此处查看其文档。

    Next, we need to set SWR’s global deduping interval to zero. We can do that in one of two ways. The simplest way is to wrap your components in SWRConfig like below.

    接下来,我们需要将SWR的全局重复数据删除间隔设置为零。 我们可以通过以下两种方式之一来做到这一点。 最简单的方法是将组件包装在SWRConfig如下所示。

    However, with this approach, we need to declare SWRConfig over and over again, leading to a lot of boilerplate and duplication. Luckily, testing library allows us to customize our render functions. We can make use of a custom render function to reduce this boilerplate.

    但是,使用这种方法,我们需要SWRConfig遍地声明SWRConfig ,这导致了很多样板和重复。 幸运的是,测试库允许我们自定义渲染功能。 我们可以使用自定义渲染功能来减少这种样板。

    To use our custom render function, we simply replace any testing library imports with imports from our test utility file.

    要使用我们的自定义渲染功能,我们只需将所有测试库导入替换为来自测试实用程序文件的导入即可。

    概要 (Summary)

    That’s it for today! When I first started using useSWR it took me a while to figure out why my tests were failing. I hope this helps to clear up any confusion pairing useSWR with React Testing Library.

    今天就这样! 刚开始使用useSWR时,我花了一段时间才弄清楚为什么测试失败。 我希望这有助于清除React测试库中的任何混淆配对useSWR。

    翻译自: https://medium.com/frontend-digest/using-testing-libary-with-useswr-f595919de2fd

    相关资源:四史答题软件安装包exe
    Processed: 0.011, SQL: 10