'Paste test in cypress in reactjs project
Any ideas how to simulate Paste action in Cypress in a bundle with React?
My test should check value right after paste action.
I found few solutions based on DOM manipulation because as the authors say it pastes changes directly to DOM input field and then envoke change event.
My tried cy.get(selector).invoke('val', 'copy-pasted text').trigger('change');
These solutions dont work as expected because React manipulates the DOM it-self hence the "pasting" by suggested ways pushes changes directly to input values and violates React workflow.
Thanks
Solution 1:[1]
I think this code could help you:
add to commands:
Cypress.Commands.add("paste", { prevSubject: true }, (selector, pastePayload) => {
// https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event
cy.wrap(selector).then($destination => {
const pasteEvent = Object.assign(new Event("paste", { bubbles: true, cancelable: true }), {
clipboardData: {
getData: () => pastePayload
}
});
$destination[0].dispatchEvent(pasteEvent);
});
});
usage:
cy.getByTestId("some-input-test-id").paste('some text');
The main difference between this and other examples from the internet is that your plugin could have problems catching what was "really" paste. So ie callback onItemsPaste
in blueprint would not catch anything. Original version.
Solution 2:[2]
The React Testing Library will fire the change event in a React app.
Ref How do I trigger a change event on radio buttons in react-testing-library
I wrapped it in a Cypress custom command for convenience.
Seems the element wants to be focused first.
import { fireEvent } from "@testing-library/react";
Cypress.Commands.add('fireEvent', {prevSubject: true}, (element, event, value) => {
element.focus()
fireEvent[event](element[0], { target: { value } });
})
...
it('fires change event', () => {
cy.get(selector).fireEvent('change', 'copy-pasted text');
/*
Test react re-render effects here with re-tryable commands,
e.g should(), not expect()
*/
});
Is this a Paste test?
There is a paste event, so perhaps 'change' is not really testing the scenario. Is there a difference between typing and pasting? Will circle back to this.
BTW I use
cy.get(selector).focus().clear().type('copy-pasted text');
without a problem.
The only caveat, as above, subsequent commands must be retryable to give React time to process (or add cy.wait(100)
).
Solution 3:[3]
cy.window().its('navigator.clipboard')
.invoke('readText').then((data) => {
console.log(data);
})
Should do the trick.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Darex1991 |
Solution 2 | |
Solution 3 |