使用赛普拉斯测试重定向到新路由

Sea*_*lus 12 javascript testing mocha.js cypress

我正在使用赛普拉斯来测试我的Web应用程序.

此代码段目前有效并将提交新内容:

describe('The Create Page', () => {
  it('successfully creates a thing', () => {
    cy.visit('/create')
    cy.get('input[name=description]').type('Hello World')
    cy.get('button#submit')
      .click()

    // After POST'ing this data via AJAX, the web app then
    // receives the id of the new thing that was just created
    // and redirects the user to /newthing/:id
    // How do I test that this redirection worked?
  })
})
Run Code Online (Sandbox Code Playgroud)

正如评论所示,我不知道如何测试重定向到新路由是否有效.我可以在浏览器模拟中看到重定向工作,我只是想为它添加一个测试.

谢谢!!!

Jen*_*ane 17

您需要做的是声明url处于预期状态.

赛普拉斯有许多命令可用于对url进行断言.具体来说,cy.url(),cy.location()cy.hash()可满足您的要求.对您的用例来说,最好的例子可能是:

cy.location('pathname').should('eq', '/newthing/:id')
Run Code Online (Sandbox Code Playgroud)

  • 所以...我的网络应用程序正在发布的这台服务器可能需要很长的时间才能响应(比如超过十秒)...我仍然遇到这个错误:CypressError: Timed out retrying: E​​xpected '/create' to equal '/newthing/:id' ...我可以更改 cypress 继续尝试某件事的时间吗?另外,谢谢您的帮助,非常感谢! (4认同)
  • 是.您可以在这里详细了解这些定时重试的工作原理[这里](https://on.cypress.io/introduction-to-cypress#Applying-Timeouts).从本质上讲,赛普拉斯将不断检查位置的路径,直到它与您的断言(`/ newthing /:id`)匹配或直到它超时.默认超时为4000毫秒.你可以通过将一个超时选项传递给`cy.location()`来增加这个时间:`cy.location('pathname',{timeout:10000}).should('eq','/ newthing /:id' )` (4认同)