Custom Command
Learn how to write `authentication custom command` for UI integration tests.
We'll cover the following
Overview
As we have created a custom signup command for the E2E tests, we should also create an authentication command for the UI Integration Tests too. It will be way far simpler because we do not need a real signup/authentication, we just need the front-end to think that it’s authenticated.
We must set the jwt
token into the local storage. Let’s write the authenticateIntegration
custom command:
authenticateIntegration
custom command.
Where can we get a valid jwt
? From the signup.json
fixture!
File: cypress/fixtures/users/signup.json
{
"user": {
"username": "tester",
"email": "user@realworld.io",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkN2ZiNmVhZDkzZWQ5MDhiMGU3MDMzYiIsInVzZXJuYW1lIjoidGVzdGVyIiwiZXhwIjoxNTczODM4NTg3LCJpYXQiOjE1Njg2NTA5ODd9.jeAccqZi6dOqokwjRPFl4fzHE5s5p8sB32NgXwlgrxQ"
}
}
Cypress allows us to read the fixtures using the cy.fixture
command. All we need to do is:
-
Read the fixture
-
Read the contained token
-
Set the
jwt
token
The command code is the following:
File: cypress/support/authentication/authenticate-integration.js
Cypress.Commands.add("authenticateIntegration", () => {
cy.fixture("users/signup")
.its("user")
.should(
user =>
expect(user)
.to.have.property("token")
.and.to.be.a("string").and.not.to.be.empty
)
.then(user => localStorage.setItem("jwt", user.token));
});
Please note that there are some assertions about the fixture content itself. The goal is always the same: to learn more from assertion feedback. If we change the fixture content accidentally, the command will prompt us with a useful message.
The test that navigates the home page leveraging an already “authenticated” user is as following:
Note: You can see the cypress UI better by opening the link next to Your app can be found at:
Get hands-on with 1200+ tech skills courses.