簡體   English   中英

Mocking 使用 Jest 向上 CTRL + V 事件

[英]Mocking up CTRL + V event using Jest

我正在構建一個應用程序,它從剪貼板讀取 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()); 
    
});

首先,我是 mocking 和 CSV 和navigator.clipboard.readText() function。 然后,我試圖觸發一個CTRL + V事件。

問題是粘貼事件沒有被觸發。 如何在 Jest 中模擬它?

這篇文章回答了這個問題。 我需要為鍵盤事件添加bubbles: true因為我正在將事件發送到document ,所以window沒有看到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM