1. 25
    Set up Testing Globals in an Application with Jest
    1m 54s

Set up Testing Globals in an Application with Jest

Andy Van Slaars
InstructorAndy Van Slaars

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

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.

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

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

[00:28] 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.

[00:39] 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.

[00:56] 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.

[01:11] 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.

[01:23] I'll save the test file. I'll paste them into testsetup.js. Now I've just moved those into the setup.

[01:32] 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.

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

Brendan Whiting
Brendan Whiting
~ 3 years ago

FYI now getting deprecation warning:

Option "setupTestFrameworkScriptFile" was replaced by configuration "setupFilesAfterEnv", which supports multiple paths.

This new flag takes an array:

module.exports = {
    setupFilesAfterEnv: ['<rootDir>/testSetup.js']
};
Andy Van Slaars
Andy Van Slaarsinstructor
~ 3 years ago

FYI now getting deprecation warning:

Option "setupTestFrameworkScriptFile" was replaced by configuration "setupFilesAfterEnv", which supports multiple paths.

This new flag takes an array:

module.exports = {
    setupFilesAfterEnv: ['<rootDir>/testSetup.js']
};

This is a change that was made in Jest 24, which was just released 2 days ago. Nice to see useful deprecation messages 🙂