首页 > 解决方案 > 使用 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 中模拟它?

标签: javascripttestingjestjs

解决方案


这篇文章回答了这个问题。我需要添加bubbles: true到键盘事件,因为我将事件发送到document,所以window没有看到它。


推荐阅读