DEV Community

Eric Douglas
Eric Douglas

Posted on

How to configure Jest on a Next.js project

You just need to follow few steps to have Jest enabled in your Next.js application.

Let's see how to do this!

1. Install the dependencies

npm i -D babel-jest jest
Enter fullscreen mode Exit fullscreen mode

2. Add the test script to run yor tests

Inside your package.json file, add this line in the scripts section:

"test": "jest --watch"
Enter fullscreen mode Exit fullscreen mode

Now, all you need to do is (after we finish the setup), type npm test on you terminal.

3. Setup .eslintrc.json

If you are using ESLint, you will need to tell it to stop warning you about Jest functions.

Create a file called .eslintrc.json if you don't have one, and add the following code in the env section:

{
    "env": {
        "jest": true
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Final step: .babelrc

Just create a file called .babelrc and put this inside of it:

{
  "presets": ["next/babel"]
}
Enter fullscreen mode Exit fullscreen mode

And that's it! If you need configure some thing particularly related to your project (like ignore certain folder), you can take a look at this file and this folder.

Bye! 👋

Top comments (3)

Collapse
 
jbranchaud profile image
Josh Branchaud

Without Step 4, I got a pretty obscure error about needing to add @babel/plugin-transform-react-jsx to the plugins section of my Babel config in order to get support for the experimental syntax that is 'jsx'.

Adding .babelrc with the specified preset fixed it. Thanks for documenting these steps!

Collapse
 
philval profile image
Philip Valentino

Thank you Eric! This a) works b) was horrible trying to find a solution. Is the Next.js team aware I wonder ?

Collapse
 
bengrunfeld profile image
Ben Grunfeld

I had to add the following to my .babelrc.

"env": {
    "test": {
        "presets": ["next/babel"]
    }
}
Enter fullscreen mode Exit fullscreen mode