javascript 使用 Cypress 测试重定向到新路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46839520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:57:53  来源:igfitidea点击:

Testing a redirect to a new route with Cypress

javascripttestingmochacypress

提问by SeanPlusPlus

I am using Cypressfor testing my web application.

我正在使用Cypress来测试我的 Web 应用程序。

This snippet currently works and will submit a new thing:

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

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

As the comment illustrates, I am not sure how to test whether or not the redirection to the new route works. I can see it in the browser simulation that the redirect works, I just want to add a test for it.

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

Thanks!!!

谢谢!!!

回答by Jennifer Shehane

What you need to do is assert that the url is in the expected state.

您需要做的是断言 url 处于预期状态。

There are many commands in Cypress that can be used to make assertions about the url. Specifically, cy.url(), cy.location()or cy.hash()may meet your requirements. Probably the best example for your use case would be this:

Cypress 中有许多命令可用于对 url 进行断言。具体来说,cy.url()cy.location()cy.hash()可满足您的要求。您的用例的最佳示例可能是这样的:

cy.location('pathname').should('eq', '/newthing/:id')