javascript - 使用 Jest 模拟 CTRL + V 事件
问题描述
我正在构建一个从剪贴板读取 CSV 并将其转换为 HTML 表格的应用程序。
这是测试:
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import App from './App';
test('Paste CSV and displays table correctly', async () => {
let csv = [
['key', 'road', 'coord.lat', 'coord.lng', 'elem'],
['1', 'C-58', 42.02, 2.82, ''],
['2', 'C-32', 41.35, 2.09, ''],
['3', 'B-20', 41.44, 2.18, '']
].map(e => e.join(`\t`)).join(`\n`);
Object.assign(navigator, {
clipboard: {
readText: () => csv
}
});
await render(<App />);
document.dispatchEvent(
new KeyboardEvent("keydown", {
key: "v",
ctrlKey: true,
metaKey: true
})
);
await waitFor(() => expect(getByText('C-58')).toBeInTheDocument());
});
首先,我正在模拟 CSV 和navigator.clipboard.readText()
函数。然后,我试图触发一个CTRL+V事件。
问题是粘贴事件没有被触发。如何在 Jest 中模拟它?
解决方案
这篇文章回答了这个问题。我需要添加bubbles: true
到键盘事件,因为我将事件发送到document
,所以window
没有看到它。
推荐阅读
- javascript - socket.io 仅发送文本中的差异
- c# - 从基类(或共享接口)引用中获取派生(通用)类成员
- python - python中的字典没有显示正确的响应
- javascript - Javascript 奇怪的输出
- python - 尝试将dict转换为字符串时无法为数组分配内存
- java - 我不断收到 java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' 错误,尽管它已经确认他们是用户
- android - 如何在设置recyclerView时删除两行之间的白色
- react-query - 在数据获取期间显示全局微调器
- ruby-on-rails - Ubuntu 在后台运行 Puma 和 Sidekiq 作为守护进程
- sql - 比较 PL SQL 中同一列在 2 天内的值