简体   繁体   English

Mocking 使用 Jest 向上 CTRL + V 事件

[英]Mocking up CTRL + V event using Jest

I'm building an app that reads a CSV from the clipboard and turns it into an HTML table.我正在构建一个应用程序,它从剪贴板读取 CSV 并将其转换为 HTML 表。

Here is the test:这是测试:

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()); 
    
});

First, I'm mocking up the CSV and the navigator.clipboard.readText() function.首先,我是 mocking 和 CSV 和navigator.clipboard.readText() function。 Then, I'm trying to fire a CTRL + V event.然后,我试图触发一个CTRL + V事件。

The problem is that the paste event isn't being fired.问题是粘贴事件没有被触发。 How can I simulate it in Jest?如何在 Jest 中模拟它?

This post answers the question.这篇文章回答了这个问题。 I needed to add bubbles: true to the keyboard event because I was dispatching the event to document , so window wasn't seeing it.我需要为键盘事件添加bubbles: true因为我正在将事件发送到document ,所以window没有看到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM