如何使用自定义挂钩测试React组件

时间:2019-12-29 12:16:48

标签: reactjs react-hooks

给出一个简单的自定义钩子(我知道该如何测试):

const useCounter = () => {
  const [value, setValue] = useState(0)

  const increase = () => {
    setValue(value + 1)
  }

  return {
    value, 
    increase
  }
}

以及使用它的组件:

const App = (props) => {
  const { value, increase } = useCounter()

  return (
    <div>
      <div>{value}</div>
      <button onClick={increase}>
        plus
      </button>
    </div>
  )
}

如何测试组件? 这样做的“正确方法”是什么? 我是否必须模拟自定义钩子?怎么样?

2 个答案:

答案 0 :(得分:2)

假设您正在使用Jest和Enzyme进行单元测试,我将使用Enzymeshallow rendering APIApp组件包装到一个浅层包装中。

然后,我将使用.find()查找button元素,并在该元素上使用.simulate('click'),以模拟按钮上的onClick事件,这样increase方法将被调用。

然后,我将继续检查预期的结果和行为。

这里简要介绍了如何完成此操作:

import { shallow } from 'enzyme';
import * as React from 'react';

describe('<App />', () => {

  it('test for onClick', () => {
    const wrapper = shallow(<App />);
    wrapper.find('button').simulate('click');

    // do the rest here
    // expect().....
  });

})

答案 1 :(得分:1)

您不需要模拟它。在测试中运行App时,它将仅使用您的自定义钩子。

如果您想以某种方式专门针对测试修改其行为,则必须对其进行模拟。