How can I execute code beforeall test suites in Cypress?
While executing code before all tests can be convenient, this approach lacks flexibility for future variations in your individual test files, such as:
- Seeding the database differently for one test.
- Logging in as a different user with different permissions.
- Performing an action in
onBeforeLoad
once.
Therefore, I recommend placing the login command in a before
hook within each individual spec file. Additionally, to avoid sharing any state between tests, I further recommend placing your login command in a beforeEach
hook.
You can place the login code in the cypress/support/index.js file. This way, the login process runs once before all tests.
Create a custom command for login in cypress/support/commands.js:
Cypress.Commands.add('login', () => {
cy.request({
method: 'POST',
url: '/login', // your login endpoint
body: {
username: 'your-username',
password: 'your-password'
}
}).then((resp) => {
window.localStorage.setItem('authToken', resp.body.token);
});
});
Call the custom login command in cypress/support/index.js:
before(() => {
cy.login();
});
The above approach helps you tests suite with Cypress beforeall.
You can also use Cypress plugins to execute code once before running all tests. Modify the cypress/plugins/index.js file to include your login logic.
Setup the login process in cypress/plugins/index.js:
module.exports = (on, config) => {
on('before:run', () => {
// Perform the login process
return cy.request({
method: 'POST',
url: '/login', // your login endpoint
body: {
username: 'your-username',
password: 'your-password'
}
}).then((resp) => {
config.env.authToken = resp.body.token;
return config;
});
});
};
Ensure you set the authorization header using the token from the environment variable in your tests.
Cypress.Commands.add('setAuthToken', () => {
cy.window().then((win) => {
win.localStorage.setItem('authToken', Cypress.env('authToken'));
});
});
beforeEach(() => {
cy.setAuthToken();
});
This helps you achieve a single login process running all your tests with the beforeall method while maintaining flexibility for individual test variations.