原文:https://css-tricks.com/testing-react-hooks-with-enzyme-and-react-testing-library/ 当你开始在应用中使用React Hooks时,你需要确保编写的代码是可靠的。确保代码没有bug的一种方法就是编写测试用例。测试React hooks与测试一般程序的方式没有太大区别。 在本教程中,我们将了解如何通
另一方面,如果你试图在不使用render()函数的情况下调用自定义hooks,也会在终端中看到错误,终端会指出hooks只能在函数组件中调用: 这么看来,测试自定义钩子确实有些棘手。 不过,别灰心,我的解决办法马上就要来了! 使用renderHook() 测试自定义 Hooks 要在React 中测试自定义钩子,我们可以使用 React Testing Library 测...
react-hooks-testing-library Simple and complete React hooks testing utilities that encourage good testing practices. The problem You're writing an awesome custom hook and you want to test it, but as soon as you call it you see the following error: Invariant Violation: Hooks can only be called...
Importing@testing-library/react-hooks/dont-cleanup-after-each.jsin test setup files will disable the auto-cleanup feature. For example, inJestthis can be added to yourJest config: module.exports={ setupFilesAfterEnv:[ '@testing-library/react-hooks/dont-cleanup-after-each.js' ...
在Testing library 里面就提供了一个 @testing-library/react-hooks 的扩展库,专门用于测试 react hooks。 该扩展库对应的官网地址:https://react-hooks-testing-library.com/ 快速上手示例 首先我们有如下的自定义 Hook: // 自定义 hook// 这是一个计数器的自定义 hook// 内部维护了一个计数的值,以及修改这...
That setup function is pretty handy. Seems like a good opportunity for an abstraction. Well, we already have one! It’s called React Hooks Testing Libr
React-hooks-testing-library可以完成我们之前讨论的所有内容甚至更多。比如,它会处理container的挂载和卸载,因此你不必在测试文件中重复这些操作,这使得我们集中精力测试hook。 它带有一个renderHook函数,返回rerender方法和result对象。此外它还会返回与waitFor类似的wait方法,你不必自己去实现。 下面是我们在React-hooks-te...
我想测试api调用和返回的数据,应该显示在我的功能组件内。我创建了一个列表组件来执行api调用。我希望返回的数据能够显示在组件中,并使用useState hook实现此目的。组件看起来像这样:cons...Testing api call inside useEffect using react-testing-library
如果我们用了它,会变成这样:import{renderHook,act}from'@testing-library/react-hooks'importuseUndo...
@testing-library[1] 是一系列建立在 DOM Testing Library[2](@testing-library/dom)基础上的包的集合。用来测试 UI 组件,不鼓励测试实现细节(比如组件内部状态、方法甚至生命周期),而是鼓励从用户使用的角度进行测试。作为初级教程,篇幅有效,本文只讨论 @tes…