In order to catch errors that are produced in all parts of the hook's lifecycle, the test harness used to wrap the hook call includes anError Boundarywhich causes asignificant amount of output noisein tests. To
Sometimes we need to test a hook with different context values. By using the initialProps option and the new props of rerender method, we can easily do this: import { renderHook, act } from '@testing-library/react-hooks' import { CounterStepProvider, useCounter } from './counter' test(...
完整代码看这里 https://testing-library.com/docs/react-testing-library/example-intro/#full-example。 案例二: import{render}from'@testing-library/react'import'@testing-library/jest-dom'test('renders a message',()=>{const{asFragment,getByText}=render(<Greeting/>)expect(getByText('Hello,world!
React-hooks-testing-library可以完成我们之前讨论的所有内容甚至更多。比如,它会处理container的挂载和卸载,因此你不必在测试文件中重复这些操作,这使得我们集中精力测试hook。 它带有一个renderHook函数,返回rerender方法和result对象。此外它还会返回与waitFor类似的wait方法,你不必自己去实现。 下面是我们在React-hooks-te...
React hooks testing library React-hooks-testing-library,是一个专门用来测试React hook的库。我们知道虽然hook是一个函数,可是我们却不能用测试普通函数的方法来测试它们,因为它们的实际运行会涉及到很多React运行时(runtime)的东西,因此很多人为了测试自己的hook会编写一些TestComponent来运行它们,这种方法十分不方便而...
Testing: import {renderHook, act} from '@testing-library/react-hooks'import {useCounter}from'../use-counter'test('exposes the count and increment/decrement functions', () =>{const {result} =renderHook(useCounter)expect(result.current.count).toBe(0)act(()=>result.current.increment()) ...
在React Hook实战指南中我们提到Hook就是一些函数,所以对Hook进行单元测试其实是对一个函数进行测试,只不过这个函数和普通函数的区别是它拥有React给它赋予的特殊功能。在讲如何对Hook进行测试之前我们先来了解一下我们要用到的测试框架Jest(https://jestjs.io/)和hook测试库react-hook-testing-library(https://github...
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 Library. Let’s swap our setup function for the renderHook function from @testing-library/react-hooks. ...
第一种方法的 screen 是 @testing-library/react 提供的 api,是从全局查找 dom,可以直接根据文本查(getByText),根据标签名和属性查(getByRole) 等。 其实render 方法返回的对象里也有这些 api: 个人感觉没啥必要用这种 api,直接拿到 container dom 再做 dom 操作的方式就好了。
7. react-testing-library 我一直很喜欢 react-testing-library,因为在编写单元测试时感觉不错。这个包提供了实用的 DOM 测试程序,鼓励良好的测试实践。 此解决方案旨在解决测试实施细节的问题,就像用户可以看到它们一样,而不是测试 React 组件的输入/输出。