ngconf
Published in

ngconf

Authenticating Your App for Cypress Tests

tldr;

Cypress Login Command

// authentication.commands.ts
declare namespace Cypress {
interface Chainable {
/**
* Custom command to setup login
* @example cy.login()
*/
login(): Chainable<Element>;
}
}
Cypress.Commands.add("login", () => {
const options = {
method: "POST",
url: Cypress.env("authServerTokenUrl"),
body: {
client_id: Cypress.env("client_id"),
client_secret: Cypress.env("client_secret"),
grant_type: Cypress.env("grant_type"),
username: Cypress.env("username"),
password: Cypress.env("password"),
},
form: true,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
cy.request(options).then((response) => {
window.localStorage.setItem(
"id_token_claims_obj",
JSON.stringify({
/* userInfo object */
})
);
window.localStorage.setItem("access_token", response.body.access_token);
window.localStorage.setItem("id_token", response.body.access_token);
window.localStorage.setItem(
"expires_at",
"" + new Date().getTime() + 10 * 60 * 1000
);
});
});

Use the `login` Command

// home.spec.ts
describe("Home", () => {
beforeEach(() => {
cy.login();
// other test setup
});
// e2e tests
});

Cypress Environment Variables

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store