1

我正在编写一个钩子库,并想使用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 函数?

4

0 回答 0