'How can I exclude script tag from Cypress run?

I have a script tag that has to be active in production but can't be called when Cypress is running. As we run Cypress against our prod build as well, I can't use process.env.NODE_ENV to exclude it.

Is there any way to exclude a piece of code when Cypress is running?



Solution 1:[1]

As long as you can identify the the script exactly, you can modify the page source before it loads with cy.intercept()

cy.intercept(url, (req) => {
  req.continue((res) => {
    const scriptToRemove = '<script something-that-defines-the-script></script>'
    res.body = res.body.replace(scriptToRemove, '')
  })
}).as('page')

cy.visit(url)

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 Fody