Add a beforeEach function to cypress tests to avoid copying and pasting needless code

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

DRY (Don't Repeat Yourself) is (in most cases) a good idea when it comes to programming.

E2E tests are no different - if we have actions that we want to perform before every cypress test, it would be great to define them in a single spot.

In this lesson we're going to learn how to use beforeEach command in order to visit the app homepage before every test in a suite.

Tomasz Łakomy: [00:00] We have two Cypress tests at the moment, and in both of those tests, we are visiting the home page.

[00:04] We have a bit of duplicated code. That is not terrible now, but imagine that in the future, we wanted to set some cookies or do something else entirely before each and every single test. We ideally want to abstract it away in a single function.

[00:17] Luckily, Cypress allows us to use a beforeEach function, which is going to be done before each and every single test in our suit.

[00:23] We can remove these two lines, and just place this command over here. After I save that, our tests are going to start automatically, and we can see that they are still passing. Now, our code is a little bit cleaner, because we are not repeating ourselves.

egghead
egghead
~ a minute ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today