Let's assume that you have a component that is listening to the keyboard and rendering the text in case of a CTRL
+ V
event:
javascript// Listeners and functions to assign text to the DOM aren't imlemented // for simplicity. // At some point in your code, you'll read the clipboard let text = navigator.clipboard.readText();
Let's assume that you want to mock up the navigator.clipboard.readText()
function using Jest.
The first step is to assign the function to the navigator
object:
javascriptlet random = 'Random text from the clipboard'; Object.assign(navigator, { clipboard: { readText: () => random } });
Now, you need to simulate the paste event in JavaScript (CTRL
+ V
).
To do it, you can use document.dispatchEvent()
function:
javascript// Notice how you are activating multiple keys (V, CTRL, CMD) at the same time // Important: bubbles need to be true to pass the event to the window document.dispatchEvent( new KeyboardEvent("keydown", { key: "v", ctrlKey: true, bubbles: true, metaKey: true }) );
At this point, you are ready to put everything together (example done with react-testing-library):
javascriptimport { render, screen, fireEvent, waitFor } from '@testing-library/react'; import App from './App'; test('Pasting data from the clipboard correctly', async () => { let random = 'Random text from the clipboard'; Object.assign(navigator, { clipboard: { readText: () => random } }); await render(<App />); document.dispatchEvent( new KeyboardEvent("keydown", { key: "v", ctrlKey: true, bubbles: true, metaKey: true }) ); await waitFor(() => expect(screen.getByText('Random text from the clipboard')).toBeInTheDocument()); });
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.