user687554
user687554

Reputation: 11131

Using Cypress to Test an App That Relies on OAuth

I've inherited a Node.js web app that uses relies on OAuth. Whenever you visit a page the app ensures you've authenticated. Please note, there no Angular, React, Vue, etc here. Each page is straight up HTML.

I want to test this site using Cypress. My problem is, I'm stuck on the initial redirect from the auth provider. Cypress acknowledge OAuth is a challenge.

commands.js

Cypress.Commands.add('login', (credentials) => {
  var settings = {
    'clientId':'<id>',
    'scope':'<scope-list>',
    ...
  };

  var body = `client_id=${settings.clientId}&scope=${settings.scope}...`;

  var requestOptions = {
    method: 'POST',
    url: 'https://login.microsoftonline.com/...',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: body
  }

  cy.request(requestOptions);
});

Then, in my test, I have:

context('Home', () => {
  it('Visits Successfully', () => {
    cy.login();

    cy.title().should('include', 'welcome');
  });
});

In the test runner, I see the login POST request is occurring. I confirmed that an access token is being received using a console.log, however, my title is empty. It's like the redirect after OAuth isn't happening in Cypress. However, when I visit the site in the browser, the redirect is happening as expected.

What am I missing?

Upvotes: 5

Views: 19794

Answers (1)

icecubed
icecubed

Reputation: 1500

What you might be missing is confusing between the actual UI flow and the programmatic flow of doing OAuth with a 3rd party website.

What you would want to do is to complete the programmatic login and then send the required parameters to your OAuth callback URL for your app manually in the test code.

an example is given here (though it uses a different grant type it gives you an idea) https://auth0.com/blog/end-to-end-testing-with-cypress-and-auth0/#Writing-tests-using-Cypress-Login-Command

another issue on the cypress github that deals with a similar problem https://github.com/cypress-io/cypress/issues/2085

this also might help: https://github.com/cypress-io/cypress-example-recipes/blob/master/examples/logging-in__single-sign-on/cypress/integration/logging-in-single-sign-on-spec.js

Upvotes: 4

Related Questions