Cypress and Script Injection inside test scenario

Viewed 5673

I am pretty new to Cypress and at the moment I am trying to test a webpage that uses browser extension I created. This extension only injects a set of JS and CSS files to the webpage and I want to simulate the same thing in my integration tests to be able to inject the libraries and test the behavior. I was wondering if there is a way to access document object from Cypress test to inject CSS or JavaScript to the head of the webpage.

1 Answers

Yes, there is. Cypress is actually running in the browser, and although commands are queued asynchronously, you can queue up native JS code to be run, like so:

cy.get("html").then(() => {
    document.querySelector("div.myDiv").innerHTML = "...";
    // ...
});

If you are trying to target or modify a specific element, you can get it via Cypress to take advantage of automatic retries to wait for the element to exist before operating on it:

cy.get("div.myDiv").then(elem => {
    elem.innerHTML = "...";
    // ...
});
Related