如何使用赛普拉斯测试客户端重定向到第 3 方站点? [英] How can I test a client-side redirect to a 3rd party site with Cypress?

查看:98
本文介绍了如何使用赛普拉斯测试客户端重定向到第 3 方站点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Cypress 提供了一种使用 request:

Cypress offers a simple way to test for server-side redirects using request:

cy.request({
  url: `/dashboard/`,
  followRedirect: false, // turn off following redirects
}).then((resp) => {
  expect(resp.redirectedToUrl).to.eq('http://example.com/session/new')
})

然而,这不适用于客户端重定向,因为页面在重定向发生之前已成功加载,这意味着响应是针对页面的,而不是针对重定向的.

However this doesn't work for client-side redirects because the page is loaded successfully before the redirect happens, meaning the response is for the page, not for the redirect.

如何测试客户端重定向?

我需要一种方法来捕获重定向并验证:

I need a way of catching the redirect and verifying that:

  • 发生了
  • 到了正确的网址.

注意:

  • 我不想跟随重定向离开正在测试的应用程序.我不是在测试整个身份验证流程.我只需要知道有重定向.
  • 我无法更改此身份验证流程.重定向是不可避免的.
  • 重定向发生在初始化期间,而不是任何用户交互的结果.
  • 重定向使用:window.location.href = url
  • 请参阅下面我的回答以尝试解决此问题.

推荐答案

Gleb Bahmutov 在 处理window.location.replace,将源码中的window.location重命名为window.__location,即有效的存根.

Gleb Bahmutov has an approach at Deal with window.location.replace, which renames window.location in the source to window.__location which is effectively the stub.

它使用cy.intercept()来修改加载页面之前它点击浏览器,即在window.location之前 被实例化并成为一个完全不可变/不可破坏的对象.

It uses cy.intercept() to modify the loading page before it hits the browser, i.e before window.location is instantiated and becomes a totally immutable/incorruptible object.

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')
})

此存根 replace,但同样适用于 href setter.

This stubs replace, but the same should work for the href setter.

这篇关于如何使用赛普拉斯测试客户端重定向到第 3 方站点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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