重定向至不同来源(跨来源)的Cypress测试 [英] Cypress testing of redirects to different origins (cross-origin)

查看:0
本文介绍了重定向至不同来源(跨来源)的Cypress测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

根据Cypress的文档,我认为我需要使用cy.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安全违规而崩溃。

推荐答案

查看Deal with 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')
})

这篇关于重定向至不同来源(跨来源)的Cypress测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆