javascript - 如何使用 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
. 我做错了什么 ?
解决方案
link.simulate('click') - 应该去工作!
推荐阅读
- events - 当用户离开(或被移除)团队时,与 team_join 等效的 slack 事件是什么
- django - 在 DRF 路由中定义名称空间
- android - 真实设备未在 android studio 中显示
- .net - excel vba sum multi sheet得到运行时错误1004:应用程序定义或对象定义错误
- sql - 如果列值低于其他列,则选择条件
- laravel-5.5 - 如何从数据库中获取单个值而不是 laravel 中的数组?
- ios - ContentViews Subview 在 UIScrollView iOS 中没有动态改变高度
- python - 如何获取元组列表的元素
- c# - 在 C# 中使用表示文件路径的字符串变量?
- python - groupby 在两列中的唯一值计数