测试预期事件的反应挂钩

时间:2020-05-04 20:35:41

标签: reactjs react-hooks-testing-library

我正在编写一个钩子库,并希望使用react-hooks-testing-library编写单元测试。我有一个帮助处理表单状态“ use-form”的钩子,它只是用于从React文档从表单状态更新的推荐模式的包装:

const useForm = initialState => {
  const [state, setState] = useState(initialState);
  const handleChange = (eventOrValue, fieldName) => {
    if (eventOrValue.nativeEvent && eventOrValue.nativeEvent instanceof Event) {
      // if a react synthetic event...
      setState({
        ...state,
        [eventOrValue.target.name]:
          eventOrValue.target.type === 'checkbox'
            ? eventOrValue.target.checked
            : eventOrValue.target.value
      });
    } 
  return [state, handleChange];
};

到目前为止我的测试-

  test('should update state on change', () => {
    const { result } = renderHook(() =>
      useForm({
        foo: 'bar'
      })
    );
    const [draft, handleChange] = result.current;

    //handleChange(new Event????)

    expect(draft.foo).toBe('xxx');
  });

如何将事件传递给钩子的handleChange函数?

0 个答案:

没有答案