javascript - 赛普拉斯测试重定向到不同来源(跨域)
问题描述
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
解决方案
看看处理 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')
})
推荐阅读
- angular - Angular 6 - http错误的返回值
- android - Flutter:默认标签栏控制器在滑动后不保持状态
- javascript - 将函数传递给 React 中的组件
- raml - RAML Osprey-Mock-Service TypeError:无法读取 null 的属性“absolutePath”
- asp.net-mvc - Sitecore 或 IIS URL 重写中的 301 重定向
- magento - Magento 1 - 为什么默认的联系我们路径是“/contacts”?
- unix - 将差异与抑制通用行和上下文选项并排结合
- docker - 更新 Jenkins 后 Docker 停止工作
- python - Python 无法在 PowerShell 中工作以键入脚本
- r - R图形:如何使VennDiagram中的对象与cowplot plot_grid兼容?