Zer*_*rty 2 reactjs jestjs enzyme
在基于类的组件中,我可以通过执行以下操作轻松访问状态:
const control = shallow(<Test />);
control.state()
Run Code Online (Sandbox Code Playgroud)
对于像下面这样的基于钩子的组件,我如何count从我的测试中访问?
const Test = () => {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>Count</button>
<div>{count}</div>
</>
)
}
Run Code Online (Sandbox Code Playgroud)
这是不可能的,也不应该如此,因为状态是一个实现细节。如果将状态重命名为myCount,组件仍然可以工作,但测试会失败。
但是,由于您渲染了计数,因此您可以简单地期望渲染正确的计数。
使用示例react-testing-library:
import { render, fireEvent } from 'react-testing-library'
const rendered = render(<Test />)
rendered.getByText(0) // Test that 0 is present in the DOM
fireEvent.click(rendered.getByText('Count'))
rendered.getByText(0) // Test that 1 is present in the DOM
Run Code Online (Sandbox Code Playgroud)
如果您确实想单独测试状态更新,您可以使用useReducer,并使用 轻松测试减速器jest,因为它是纯 JavaScript 函数。
| 归档时间: |
|
| 查看次数: |
5990 次 |
| 最近记录: |