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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.