原文:https://css-tricks.com/testing-react-hooks-with-enzyme-and-react-testing-library/ 当你开始在应用中使用React Hooks时,你需要确保编写的代码是可靠的。确保代码没有bug的一种方法就是编写测试用例。测试React hooks与测试一般程序的方式没有太大区别。 在本教程中,我们将了解如何通过使用带有hooks的to-do...
import{render,screen}from'@testing-library/react'import{Counter}from'./Counter'importuserfrom'@testing-library/user-event'describe('Counter',()=>{test('renders a count of 0',()=>{render(<Counter/>)constcountElement=screen.getByRole('heading')expect(countElement).toHaveTextContent('0')})tes...
使用React Testing Library的render函数渲染组件。 使用React Testing Library的screen对象获取DOM元素。ByRole是推荐的查询元素的方法。 使用@testing-library/user-event库模拟用户事件。 对渲染输出进行断言。 以下测试验证了Counter组件的功能: import{render,screen}from'@testing-library/react'import{Counter}from'./C...
import { renderHook, act } from '@testing-library/react-hooks' import { CounterStepProvider, useCounter } from './counter' test('should use custom step when incrementing', () => { const wrapper = ({ children, step }) => ( <CounterStepProvider step={step}>{children}</CounterStepProvi...
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/react-hooks 底层也是做了一些和我们上面 setup 类似的事。@testing-library/react-hooks 还提供了如何内容: 一套用来 “rerender” 使用 Hook 的组件的工具函数(用来测试依赖项变更的情况) 一套用来 “unmount” 使用 Hook 的组件的工具函数(用来测试清除副作用的情况) 一些用来等待指定...
首先,我们先编写一个自定义 Hooks,接着我们再使用 React Testing Library 对它进行测试。 下面这段代码,你看到的是我将前面计算器的逻辑提取到一个名为useCounter的自定义钩子中: // useCounter.tsximport{ useState }from"react"; typeUseCounterProps= { ...
React hooks testing library React-hooks-testing-library,是一个专门用来测试React hook的库。我们知道虽然hook是一个函数,可是我们却不能用测试普通函数的方法来测试它们,因为它们的实际运行会涉及到很多React运行时(runtime)的东西,因此很多人为了测试自己的hook会编写一些TestComponent来运行它们,这种方法十分不方便而...
我想测试api调用和返回的数据,应该显示在我的功能组件内。我创建了一个列表组件来执行api调用。我希望返回的数据能够显示在组件中,并使用useState hook实现此目的。组件看起来像这样:cons...Testing api call inside useEffect using react-testing-library
测试react 组件和 hooks 可以使用 @testing-library/react 这个包,然后测试用例使用 jest 来组织。 这两个包 cra 都给引入了,我们直接跑下 npm run test 就可以看到单测结果。 App 组件是这样的: 它的单测是这么写的: 通过@testing-library/react 的 render 函数把组件渲染出来。