javanewbie
javanewbie

Reputation: 9

Cypress cy.visit() is not redirecting to correct URL

I am trying to bypass the UI login by using cy.request() to log a user in and cy.visit() to go to the restricted route. I have followed this doc: https://docs.cypress.io/guides/end-to-end-testing/testing-your-app#Bypassing-your-UI

However, the test fails because the visit URL ('http://localhost:3000/join-or-create') is not loaded and instead the home page URL is loaded (http://localhost:3000/).

This is my test code:

describe('when user is signed in but has not joined a group', () => {
  beforeEach(() => {
    cy.request('POST', 'http://localhost:5000/api/testing/reset');
    const user = {
      name: 'Joe Bloggs',
      email: '[email protected]',
      password: 'Password',
    };
    cy.request('POST', 'http://localhost:5000/register', user);
    cy.request('POST', 'http://localhost:5000/sign-in', user);
    cy.visit('http://localhost:3000/join-or-create');
  });

  it.only('should allow a logged in user to join or create a group', () => {
    cy.contains('Join a group');
    cy.contains('Create a group');
  });
});

If I change cy.contains('Join a group'); to cy.contains('Welcome'); (which is content on the URL 'http://localhost:3000/') then the test passes.

If I use:

cy.visit('http://localhost:3000');
cy.get('[data-testid="email"]').type('[email protected]');
cy.get('[data-testid="password"]').type('Password');
cy.contains('sign in').click();

instead of cy.visit('http://localhost:3000/join-or-create'); the test passes.

The output of the test body shows that is redirecting to a new URL 'http://localhost:3000/' (as shown in the screenshot below) but I can't figure out why.

enter image description here

Thanks for any help.

Upvotes: -1

Views: 1931

Answers (1)

Sariget
Sariget

Reputation: 175

In the bypass code, check the response from the POST request

cy.request('POST', 'http://localhost:5000/sign-in', user)
  .then(response => console.log(response))

to see what tokens are returned.

Then in the form-login code, look at what happens to the same token after cy.contains('sign in').click() and see where the browser stores same token.

That's probably the step missing in the bypass code. You'll need to add something to do the same, e.g

cy.request('POST', 'http://localhost:5000/sign-in', user)
  .then(response => {
    const token = response.body.token;  // figure out where the token is in response
    cy.setCookie(token);                // figure out where the app want's the token
  })

It's also difficult to tell from the question what URL you need to cy.visit() in the bypass code, but there's only a couple of them so try both permutations.

Upvotes: 3

Related Questions