1

I'm building an app that reads a CSV from the clipboard and turns it into an HTML table.

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. Then, I'm trying to fire a CTRL + V event.

The problem is that the paste event isn't being fired. How can I simulate it in Jest?

Erik Martín Jordán
  • 4,332
  • 3
  • 26
  • 36

1 Answers1

0

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.

Erik Martín Jordán
  • 4,332
  • 3
  • 26
  • 36