Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

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

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Reduce Code Duplication in Cypress Tests with beforeEach

    Andy Van SlaarsAndy Van Slaars

    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.

    cypressCypress
    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    Instructor: 00:00 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.

    00:17 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.

    00:37 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.

    00:53 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.

    01:12 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.

    Discuss

    Discuss