jeudi 18 mars 2021

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.

Here is the test:

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?

Aucun commentaire:

Enregistrer un commentaire