How can I execute code before all tests suite with Cypress

Florian F picture Florian F · Jan 5, 2018 · Viewed 25.1k times · Source

Basically, I want to login once before all my tests are executed. My tests files are split on several files.

Should I call my login command in each test file using the before hook or is there any way to to do it once before all tests ?

Answer

Jennifer Shehane picture Jennifer Shehane · Jan 8, 2018

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.