我正在构建一个应用程序,该应用程序从剪贴板读取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
没有看到它