skip to Main Content

I want to write Cypress tests for a website that is being loaded as an iFrame in a parent environment. The parent environment injects metatags when loading the site, and I need to replicate this functionality in Cypress.

Do to so, I need to fetch the contents of a URL passed by a test runner, modify the <head></head> of the HTML to add meta tags like this:

metaTag.setAttribute("dark-mode", "true");

then load the site with the metadata. However, if I fetch the contents, add metadata, but then run cy.visit(URL), only the unmodified site is loaded.

I know Cypress allows accessing metatags, but does it support injecting them?

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to @TesterDick's suggestion, I was able to get the following to work:

      cy.visit("myurl.com", {
        onBeforeLoad: win => {
          const head = win.document.querySelector("head") as HTMLHeadElement;
          const darkModeTag = win.document.createElement("meta");
          darkModeTag.setAttribute("name", "dark-mode");
          darkModeTag.setAttribute("content", "true");
          const featureTag = win.document.createElement("meta");
          head.appendChild(darkModeTag);
        },
    

    This results in the page loading with the correct metadata set.


  2. You could add headers in the onLoad event of cy.visit().

    cy.visit('https://example.com', {
      onLoad: (win) => {
        const head = win.document.querySelector('head')
        const meta = win.document.createElement('meta')
        meta.setAttribute("dark-mode", "true")
        head.appendChild(meta)
      }
    })
    
    cy.get('head meta[dark-mode]')
      .should(
        'have.attr',
        'dark-mode',
        'true',
      )
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search