本文介绍了如何使用赛普拉斯测试客户端重定向到第 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:

注意:

推荐答案

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 方站点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 00:11