首页 > 解决方案 > 如何使用 jest、react-testing-library 在 React 中模拟元素上的点击事件

问题描述

我的组件呈现以下内容

{list.options && list.options.length > 0 ? (
<div
    data-testId="MyAlertText" onClick={onAddText}>
    Add Text
</div>
) : null}

而且,在我的测试中,我正在执行以下操作

it('Add Text link should render', () => {
    const { container, getByTestId} = render(<MyComp />);

    const link = getByTestId('MyAlertText');
    expect(link).toBeInTheDocument();
})

它运行成功

但是当我尝试运行并模拟onClick它时失败了。

在此处输入图像描述

it('Add Text link should call method', () => {
    const { container, getByTestId} = render(<MyComp />);

    const link = getByTestId('MyAlertText');
    expect(link).toBeInTheDocument();

    fireEvent.click(link );
    expect(jest.fn()).toHaveBeenCalled();
})

我尝试使用jest mock. 我做错了什么 ?

标签: javascriptreactjsjestjsreact-testing-library

解决方案


link.simulate('click') - 应该去工作!


推荐阅读