使用 Cypress 拦截和存根第三方 <script> 标签

Intercept and stub third party <script> tags with Cypress

我的用例:在网站上测试第三方小部件。

为此,我们将小部件作为 <script src='https://cdn.com/widget.js'/> 标签加载到第三方。我想做的是拦截该 JS 请求并将 https://cdn.com/widget.js 替换为 https://localhost:3000/dist/widget.js.

这样我们就可以 运行 使用本地版本的小部件进行 cypress 测试(运行 in CI on a PR),并确保 PR 不会在合并之前打破 e2e 测试。

您可以使用 blockHosts 来阻止该域中的脚本完全加载。不过,这不会让您用假的 wdiget 替换它。

要用其他内容替换响应,您可以改用 Intercept

这里有一个有趣的例子,使用这个和 stub 来替换 Google Analytics - https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/stubbing-spying__google-analytics

您可以使用 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'/>")