67

I am using Cypress for testing my web application.

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!!!

SeanPlusPlus
  • 8,663
  • 18
  • 59
  • 84

2 Answers2

94

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

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:

cy.location('pathname').should('eq', '/newthing/:id')
bryanbraun
  • 3,025
  • 2
  • 26
  • 38
Jennifer Shehane
  • 6,645
  • 1
  • 30
  • 26
  • 4
    So ... This server that my web app is POST'ing to could take a loooong time to respond (like over ten seconds) ... I still get this err: CypressError: Timed out retrying: expected '/create' to equal '/newthing/:id' ... Can I change how long cypress will keep trying a thing for? Also, thx for the help, really appreciate it!!! – SeanPlusPlus Oct 19 '17 at 23:46
  • 10
    Yes. You can read about how these timed retries work in great detail [here](https://on.cypress.io/introduction-to-cypress#Applying-Timeouts). Essentially, Cypress will continuously check the location's path until it matches your assertion (`/newthing/:id`) or until it times out. The default timeout is 4000ms. You can increase this time by passing a timeout option to `cy.location()` like so: `cy.location('pathname', {timeout: 10000}).should('eq', '/newthing/:id')` – Jennifer Shehane Oct 20 '17 at 13:56
-1

Use below code to find out the url irrespective of other parameters

cy.location().should((loc) => {
   expect(loc.pathname.toString()).to.contain('/home');
 });
Gaurav Mogha
  • 370
  • 3
  • 9