Authenticating Login With Cypress
Cypress is an impressive open-source Front-end testing tool. It helps one write Unit tests, End-to-End tests and Integration tests. The reason why I especially like Cypress is its ease in setting up, configuring and debugging.
In this article I will be highlighting how to use Cypress to create random users and to confirm user creation.
The npm package faker will be used for this. To install:
npm i faker@5.5.3
This package creates fake data that can be used in your application.
In the file you want the data to be used, in this case it's the SignUp.cy.ts file;
const faker = require('faker');
const users = {
username: faker.name.findName(),
email: faker.internet.email(),
password: faker.internet.password()
}
This block of code creates an object called users
that takes in data from faker
To use it;
describe('Testing Login Page', () => {
it('Visits the homepage', () => {
cy.visit('http://localhost:3000')
cy.get('input#username').type(`${users.username}`)
cy.get('input#email').type(`${users.email}`)
cy.get('input#password').type(`${users.password}`)
})
})
While testing, testing the SignUp and/or Login can be a bit of hassle. Cypress tests using the UI and in this way it can be difficult to confirm if the server has recieved the data sent to it.
cy.wait
, cy.intercept
can be used to work around this issue.
cy.wait
waits for a number of milliseconds or wait for an aliased resource to resolve before moving on to the next command.
The syntax is:
cy.wait(time)
cy.wait(alias)
cy.wait(aliases)
cy.wait(time, options)
cy.wait(alias, options)
cy.wait(aliases, options)
UseCase: cy.wait(2000)
Here, cypress waits for 2000 milliseconds before a carrying out an action.
An aliased route as defined using the .as() command and referenced with the '@' character and the name of the alias.
cy.intercept
is used to spy on and stub network requests.
For spying on network requests which we will be discussing, the syntax is:
cy.intercept(url)
cy.intercept(method, url)
cy.intercept(routeMatcher)
When testing if a user account has been created, cy.wait
and cy.intercept
can be used as:
describe('Testing Login Page', () => {
it('Visits homepage', () => {
cy.visit('http://localhost:3000/login')
})
it('Types in the user details', () => {
cy.get('input#username').type(`${users.username}`)
cy.get('input#email').type(`${users.email}`)
cy.get('input#password').type(`${users.password}`)
//spies on the POST method at the url indicated and is given the alias 'signup'
cy.intercept('POST', 'http://localhost:8000/api/v1/auth-token/').as('signup')
//clicking on the button sends the request
cy.get('button').click()
//uses its alias 'signup' to confirm if the status requested is successful
cy.wait('@signup').its('response.statusCode').should('eq', 200)
})
})
I hope this article helps.