'How can I execute code before all tests suite with Cypress?
Basically, I want to login once before all my tests in all files are executed.
Should I call my login command in each test file using the before hook or is there any way to do it once before all tests?
Solution 1:[1]
Short answer: You can write your login command in a before
hook within the supportFile
(the file that is loaded automatically before your other spec files). This before
hook will run before any of the code in your other test files.
Recommendations: That being said, this approach leaves little flexibility for variation in your individual test files that you may want in the future like:
- What if you want to seed the database differently for one test?
- What if you want to log in as a different user with different permissions?
- What if you need to do something in
onBeforeLoad
once?
I would recommend just having the login command in a before
hook in each individual spec file.
I would also further recommend having your login command in a beforeEach
hook to avoid sharing any state in between tests.
Solution 2:[2]
describe('Hooks', function() {
before(function() {
// runs once before all tests in the block
})
})
https://docs.cypress.io/guides/core-concepts/writing-and-organizing-tests.html#Hooks
Solution 3:[3]
I would login before EACH test because there could be things that happen in a previous test that affects the results of the current test. With a fresh login, you're starting with a clean state every time. If you want to test a "chain" of unrelated actions (action A THEN action B), then write that as a separate test, but have basic functionality in individual tests.
describe('/page'), () => {
beforeEach(() => {
cy.login() // custom command that hanldes login w/o UI
cy.visit('/page') // go to the page you are testing
})
// tests
})
You should include a beforeEach block in every test file. This block should login and navigate to the page in question.
Solution 4:[4]
I would wrap the function to execute in a before block, as others already suggested.
Now, looking at the docs, I would make that happen in the cypress/support/index.js
file.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jennifer Shehane |
Solution 2 | Hossam Mourad |
Solution 3 | Ethan Dowler |
Solution 4 | Armando Guarino |