Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept and stub third party <script> tags with Cypress

Tags:

cypress

my use case: Testing a third party widget on a website.

For that, we load the widget on the third party as a <script src='https://cdn.com/widget.js'/> tag. What I'd like to do is intercept that JS request and replace https://cdn.com/widget.js with https://localhost:3000/dist/widget.js.

This is so that we can run the cypress tests with the local version of the widget (run in CI on a PR), and make sure that the PR doesn't break the e2e tests, before merging it.

like image 895
Mohamed Oun Avatar asked Oct 15 '25 06:10

Mohamed Oun


1 Answers

You can modify the body of the initial visit using cy.intercept()

cy.intercept(url, (req) => {
  req.continue((res) => {
    res.body = res.body.replace('https://cdn.com/widget.js', 'https://localhost:3000/dist/widget.js')
  })
}).as('page')

cy.visit(url)

cy.wait('@page')
  .its('response.body')
  .should('contain', "<script src='https://localhost:3000/dist/widget.js'/>")
like image 93
Fody Avatar answered Oct 18 '25 07:10

Fody