Skip to content

Instantly share code, notes, and snippets.

@gajewsk2
Created March 31, 2020 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gajewsk2/bb68dc86d072496b7f2cdd62c92a8433 to your computer and use it in GitHub Desktop.
Save gajewsk2/bb68dc86d072496b7f2cdd62c92a8433 to your computer and use it in GitHub Desktop.
Simulating logged in users
// add new command to the existing Cypress interface
declare global {
// Would love a better way to add commands w/ TS w/o redeclaring the namespace
// eslint-disable-next-line no-redeclare
namespace Cypress {
interface Chainable {
login: any
}
}
}
export function login() {
const appState = { target: '/' };
Cypress.log({
name: 'loginViaAuth0',
});
const options = {
method: 'POST',
url: Cypress.env('AUTH_URL'),
body: {
grant_type: 'password',
username: Cypress.env('AUTH_USERNAME'),
password: Cypress.env('AUTH_PASSWORD'),
audience: Cypress.env('AUTH0_API_ID'),
scope: 'openid profile email',
client_id: Cypress.env('AUTH0_CLIENT_ID'),
client_secret: Cypress.env('AUTH_CLIENT_SECRET'),
},
};
cy.request(options).then(({ body }) => {
// eslint-disable-next-line @typescript-eslint/camelcase
const { access_token, expires_in, id_token } = body;
cy.server();
// intercept Auth0 request for token and return what we have
cy.route({
url: 'oauth/token',
method: 'POST',
response: {
access_token,
expires_in,
id_token,
token_type: 'Bearer',
},
});
// Auth0 SPA SDK will check for value in cookie to get appState
// and validate nonce (which has been removed for simplicity)
const stateId = 'test';
const encodedAppState = encodeURI(JSON.stringify(appState));
cy.setCookie(
`a0.spajs.txs.${stateId}`,
`{%22appState%22:${encodedAppState}%2C%22scope%22:%22openid%20profile%20email%22%2C%22audience%22:%22default%22}`,
);
const callbackUrl = `${Cypress.env('APP_SERVER_URI')}?code=test-code&state=${stateId}`;
return cy.visit(callbackUrl);
});
}
Cypress.Commands.add('login', login);
export default {};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment