Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Reduce Code Duplication in Cypress Tests with beforeEach


    A lot of our tests will share setup steps. Since Cypress is using Mocha under the hood, we can take advantage of existing features such as the ability to define a beforeEach block that runs before each of our tests. In this lesson we’ll refactor two tests that contain duplicate commands by moving that duplication into the beforeEach for our describe block.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: I have two terminal panes. One is running my application and build process locally, and the other one is running Cypress. Cypress is already running my form input spec file, which has two tests, focuses the input on load, and accepts input. We can see that both tests are passing.

    Let's switch to the code and see how we can refactor this a little bit. We'll notice that each one of these tests has a a call to cy.visit at the beginning. Rather than duplicating this through all of our tests, we can take advantage of the fact that Cypress is using Mocha under the hood. We can use Mocha's built-in capability to run code before each individual test.

    To remove the duplication for cy.visit, all we have to do is go to the top of our describe block. We can add a call to BeforeEach. BeforeEach is going to run for each individual it within our describe block.

    We can add our cy.visit here, visiting the root of our application. Then we can come down here and we can remove it from our first test, and then remove it again from our second test. When we save this, our test will run again, and we can verify that our tests continue to pass.

    If we come over here to the command log, we can expand this. We'll see that our visit and our XHR to get our to-dos is now happening inside this BeforeEach. If we click on accepts input, we'll see the same thing, BeforeEach running to do our visit.