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.


    Set up Testing Globals in an Application with Jest


    There are things that will happen in all of our test files that we can handle in a centralized fashion. In this lesson, we’ll create a jest configuration file and a test setup file to import utilities that we want to make available for all of our tests.



    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: If we take a look at our test file, we'll see that we're doing these two imports. We're importing jest-dom/extend-expect and this react-testing-jlibrary/cleanup-after-each. We're going to end up with multiple spec files in our project. We're probably going to want both of these included in all of those tests.

    Since we're not referencing anything specifically imported -- like we are here with render -- we don't necessarily need these to be in the test file. We just need to include them in all of our tests.

    Let's add a new file to the root of our project. We're going to call this jest.config.js. Jest config is going to export an object.

    We'll do a module.exports here. We're going to give this a setup test frameworks root file. We're going to point that to a path for a file that we'll create in a second.

    We're going to use this rootdir placeholder. This will map to our absolute path for our directory of our project and then testsetup.js. We can save that.

    In the root of our project, we'll create our testsetup.js file. I'm going to go back to app.spec. I'm going to take these two imports. I'm going to cut them.

    I'll save the test file. I'll paste them into testsetup.js. Now I've just moved those into the setup.

    Our Jest config is going to be found by convention based on the fact that it's called jest.config.js. Jest should set up our test environment with those two imports in place.

    To make sure that works, let's run npm test one more time. Our tests run without error. We have our passing test.