Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a redirect to a new route with Cypress

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

like image 865
SeanPlusPlus Avatar asked Oct 19 '17 21:10

SeanPlusPlus


People also ask

How do I test a redirect?

Open an Internet Explorer browser in the host computer and enter a URL that you specified for redirection. Verify that the webpage is opened in Internet Explorer on the guest virtual machine. Repeat this process for each URL that you want to test.

How do you handle multiple redirects in Cypress?

Using cy. on command we can catch the event called url:changed . This event returns the url which we are being redirected to, so we can feed this into an array of all our redirects and test our array instead, like this: it('passing test', () => { const urlRedirects = []; cy .


1 Answers

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') 
like image 146
Jennifer Shehane Avatar answered Sep 20 '22 03:09

Jennifer Shehane