Coverage by Jest 测试 React 组件以在单击按钮时调用函数

Coverage by Jest tests of a React component to call a function when a button is clicked

我有一个功能性的 React 组件,它呈现一个按钮,单击该按钮时,会使用传递的参数从 props 调用 handleSave 函数。我尝试用测试覆盖组件,但我无法获胜,测试在控制台中崩溃,并显示未调用该函数的错误。附上组件和测试代码:

// component
function Modal(props) {
  const { handleSave } = props;

  return (
    <button onClick={() => {handleSave('someInfo')}}>Save</button>
  )
}

// test
describe('ModalComponent', () => {
  it('should call handleSave function', () => {
    const onSaveClickMock = jest.fn();

    const component = mount(<Modal handleSave={onSaveClickMock} />);
    const button = component.find('button');
    button.simulate('click');
    expect(onSaveClickMock).toHaveBeenCalled();
  })
})

据我了解,如果像这样将 handleSave 函数直接传递给 onClick,则此测试实现将起作用:

<button onClick={handleSave}>Save</button>

当函数不仅传递给 onClick 属性,而且使用传递的参数调用时,如何实现测试?

嗯,有 a helper methodtoHaveBeenCalledWith()(别名 - toBeCalledWith()):

Use .toHaveBeenCalledWith to ensure that a mock function was called with specific arguments.

因此您的测试可能如下所示:

it('should call handleSave function with a predefined value', () => {
  const onSaveClickMock = jest.fn();
  const predefinedValue = 'someInfo';

  const component = mount(<Modal handleSave={onSaveClickMock} />);
  const button = component.find('button');
  button.simulate('click');
  expect(onSaveClickMock).toHaveBeenCalledWith(predefinedValue);
});

请注意,如果您确实要向该函数发送预定义值,则应认真考虑将其抽象为常量(并在测试中导入该常量)。这样您就不必在需要时两次更新此值。