Cypress Quick Tip: Requests

09/10/20181 Min Read — In Resources, Testing, Development

The classic use case for making direct requests to your backend outside of your front end application, is to create, login and seed the local browser with user creds so you can cleanly run whatever tests.

You could put something like this in your before each:

// set up user with your own utils or faker, depending on your needs
Cypress.Commands.add('createUser', overrides => {
cy.request({
method: 'POST',
url: '/register',
body: user,
})
.then(response => response.body.user)
});
Cypress.Commands.add('login', user => {
cy.request({
url: '/login',
method: 'POST',
body: user,
}).then(response => {
window.localStorage.setItem('token', response.body.user.token)
return response.body.user
})
});
Cypress.Commands.add('loginAsNewUser', () => {
cy.createUser().then(user => {
cy.login(user)
})
});

The other really common use case to simply to hit endpoints that are really only meant to support your test suites. Typically these are also around user creation or management but the main case is to have fixtures that can get dumped or seeded by hitting those endpoints.

You can see the sky is the limit and Cypress really can support integration and true end to end testing, it's just up to us to use the tools!

Happy testing, read the docs!