如何在 Cypress 中处理到不同来源的多个重定向

0 redirect cross-domain cypress cypress-origin

我需要访问一个两次重定向到不同来源的 URL。例如:

域名-to-visit.com -> 重定向1.com -> 最终域名.com

下面的代码适用于单个重定向:

cy.origin('redirect1.com') => {
  cy.visit('domain-to-visit.com');
}); 
Run Code Online (Sandbox Code Playgroud)

但我需要支持多个重定向。

我的本能反应是想将上面的代码包装在另一个代码中cy.origin,但尚不支持。

我如何访问domain-to-visit.com并允许其重定向到 Cypress 中的多个源?

Fod*_*ody 5

只需为您有兴趣测试某些内容的任何重定向 URL 编写一个原始命令即可。

如果您已经domain-to-visit.com -> redirect1.com -> final-domain.com并且想要在 中采取行动final-domain.com,您的代码将是

cy.visit('domain-to-visit.com');

// you can ignore the intermediate domain "redirect1.com"

cy.origin('final-domain.com') => {
  cy.get(...).should(...)           // test this page
})
Run Code Online (Sandbox Code Playgroud)

测试中间页面

如果您还想在 上测试某些内容redirect1.com,只需添加另一个cy.origin(),不是嵌套的,而是按顺序添加。

据我所知,只有当网页需要一个操作才能转到最终页面时,这才有意义。

cy.visit('domain-to-visit.com');

cy.origin('redirect1.com') => {
  cy.get(...).should(...)           // test this page
  cy.get('a[href="..."]').click()   // redirect onwards
})

cy.origin('final-domain.com') => {
  cy.get(...).should(...)           // test this page
})
Run Code Online (Sandbox Code Playgroud)

一个可重现的例子

基页.html

<meta>在标签中使用 HTML 重定向

<html>
  <head>
    <meta http-equiv="refresh" content="0; URL='http://127.0.0.1:5500/html/redirect1.html'" />
  </head>
  <body>
    <h1>Base page</h1>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

在端口 3000 上提供服务:

const http = require('http')
const fs = require('fs')

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'content-type': 'text/html' })
  fs.createReadStream('html/base-page.html').pipe(res)
})
server.listen(process.env.PORT || 3000)
Run Code Online (Sandbox Code Playgroud)

重定向1.html

单击按钮时使用 JavaScript 重定向。

在端口 5500 上提供服务:

<html>
  <body>
    <h1>Redirect 1</h1>
    <button onclick="redirect()">Redirect</button>
    <script>
      function redirect() {
        window.location = "https://example.com"
      }
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

测试

cy.visit('http://127.0.0.1:3000')
cy.get('h1').contains('Base page')                                // passes

cy.origin('http://127.0.0.1:5500/html/redirect1.html', () => {
  cy.get('h1').contains('Redirect 1')                             // passes
  cy.get('button').contains('Redirect').click()
})  

cy.origin('https://example.com', () => {
  cy.get('h1').contains('Example Domain')                         // passes
})
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述