首页 > 解决方案 > 赛普拉斯测试重定向到不同来源(跨域)

问题描述

window.location.replace我的 Web 应用程序在加载时会通过基于用户参数的方法自动将用户重定向到不同来源的 URL 。

当赛普拉斯测试我的应用程序并尝试遵循重定向时,它检测到违反same-origin安全策略并且测试崩溃。但我仍然需要测试window.location.replace是否被正确调用。

根据赛普拉斯的文档,我相信我需要使用cy.stub()来模拟该功能,以避免浏览器实际重定向到不同来源的副作用。

我尝试了几种不同的 stub 方法window.location.replace,但它们似乎都没有像我预期的那样工作。

// none of these work

cy.stub(window.location, "replace")
// TypeError: Cannot redefine property: replace

cy.stub(window, "location.replace")
// TypeError: Cannot stub non-existent own property location.replace

window.location.replace = cy.stub()
// TypeError: Cannot assign to read only property 'replace' of object '[object Location]'


cy.visit("http://localhost:3000");

expect(window.location.replace).to.be.called;
expect(window.location.replace).to.be.calledWith('https://some-other-origin.com/some/url')

我不相信我想使用,因为在重定向发生时,由于安全违规cy.location(),测试已经崩溃。same-origin

标签: javascriptredirectcypressstubweb-api-testing

解决方案


看看处理 window.location.replace。方法是window.location在加载页面之前在源中重命名。

效果如何取决于您的应用程序的结构。如果您发布一些详细信息,我可以举一个更具体的例子。

it('replaces', () => {

  cy.on('window:before:load', (win) => {
    win.__location = {                           // set up the stub
      replace: cy.stub().as('replace')
    }
  })

  cy.intercept('GET', 'index.html', (req) => {   // catch the page as it loads
    req.continue(res => {
      res.body = res.body.replaceAll(
        'window.location.replace', 'window.__location.replace')
    })
  }).as('index')

  cy.visit('index.html')
  cy.wait('@index')

  cy.contains('h1', 'First page')
  cy.get('@replace').should('have.been.calledOnceWith', 'https://www.cypress.io')
})

推荐阅读