Jest Setup
Get introduced with the Jest setup file and learn why it’s used.
We'll cover the following
Adding a Jest setup file
Since this chapter’s project will have three components (Carousel
, CarouselButton
, and CarouselSlide
), it’s going to have three test files. Rather than duplicate the Enzyme configuration logic across all three, we should move that logic into a “setup file” that will only run once whenever Jest runs our tests.
Actually, we’re going to need two files. The setup file, and a Jest configuration to point to it. Let’s start with the configuration. By default, Jest looks for a file called jest.config.js
in the root of the project:
//jest.config.js
module.exports = {
setupTestFrameworkScriptFile: './src/tests/jestSetup.js',
};
- The
setupTestFrameworkScriptFile
entry tells Jest to go ahead and “Run the file calledsrc/tests/jestSetup.js
in the root of this project before running any tests.”
Jest supports many other configuration options, but we won’t be needing them. If you’re curious, consult the official docs.
-
Now let’s create that file:
//src/tests/jestSetup.js import Adapter from 'enzyme-adapter-react-16'; import { configure } from 'enzyme'; configure({ adapter: new Adapter() });
If you’re running Wallaby or jest --watchAll
, you’ll need to restart it in order for Jest to recognize the new setup.
Linting and Project Structure
Why put the Jest setup file in the
tests
directory? Although the Jest setup file isn’t a test file, it does run in the same environment as the test files. That means that it should follow the Jest-specific linter rules defined insrc/tests/.eslintrc.js
. At this point, the setup file satisfies either set of linter rules, but that could change if the test setup grows more elaborate.It’s always useful to remember which environment each JavaScript file in your project runs in and to keep it in a directory with an appropriate ESLint configuration. Ideally, we’d move
jest.config.js
andwallaby.js
into a more precisely configured directory as well, but (as of this writing) Jest and Wallaby expect those files to live in the project root.
With the Jest setup file in place, you no longer need to run Enzyme’s configure()
method in each individual test file:
Get hands-on with 1400+ tech skills courses.