首页 > 解决方案 > 使用 fireEvent 发送值

问题描述

我正在使用fireEventfrom @testing-library/react。我声明了一个反应组件如下:

const CustomParamTest = () => {
  onButtonClick(customParam) {
    console.log(customParam);
  }

  return (
    <>
      <button 
        data-testid="custom-param-button" 
        onClick={(customParam) => onButtonClick(customParam) }
      >
        Custom param
      </button>
    </>
  );
}

我有这个测试:

describe('basic test', () => {
  test('items should be empty', () => {
    const { getByTestId } = render(<CustomParamTest />);

    const customButton = getByTestId('custom-param-button');
    fireEvent.click(customButton);
  });
});

我想要实现的是使用点击事件发送自定义参数,如下所示:

fireEvent.click(customButton, myCustomParameter);

我想访问myCustomParameter我的onButtonClick函数内部。我可以使其工作如下,但我想要一个更好的解决方案:

我创建了一个这样的自定义点击事件:

const customEvent = createEvent.click(customButton, { button: 2 });
customEvent.myCustomProp = 'customValue';
fireEvent.click(customButton, customEvent);

在我的组件中,我可以像这样访问这个值:

onClick={(e) => console.log(e.nativeEvent.myCustomProp)}

我觉得应该有更好的方法来做到这一点。

标签: reactjstestingjestjsreact-testing-library

解决方案


推荐阅读