使用 Jest 模拟 CTRL + V 事件

时间:2021-03-18 12:29:04

标签: javascript testing jestjs

我正在构建一个从剪贴板读取 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 事件。

问题是没有触发 paste 事件。我如何在 Jest 中模拟它?

1 个答案:

答案 0 :(得分:0)

这个 post 回答了这个问题。我需要将 bubbles: true 添加到键盘事件中,因为我将事件分派到 document,所以 window 没有看到它。