GoldFlsh
GoldFlsh

Reputation: 1334

How to use different jest.config.js for unit and component tests?

I am trying to create a separate suite of tests for component level testing of an app.

In this separate suite, I will need a custom test environment that bootstraps some persistence layer mocks and these tests will be housed in a separate folder in my project structure from my unit tests.

e.g. the unit tests will be nearby the code in __tests__ folders while the component tests will be in a top-level tests/ directory.

I already have most of my jest.config.js setup, but when I added the projects section to override some of the fields, specifically testMatch and testEnvironment it completely disregarded my configuration specified in global.

Now I've been reading that the projects configuration is mostly about monorepo setups, so I don't think that's the right approach.

Ideally I could just have a separate jest.config.js in my tests/ directory, but I don't see how to set that up if that even works.

Any insight into this problem would be helpful. Thanks ahead of time.

Upvotes: 11

Views: 13373

Answers (2)

GoldFlsh
GoldFlsh

Reputation: 1334

What I ended up doing was to specify separate projects in package.json

"jest": {
    "projects": [
        "<rootDir>/jest.unit.config.js",
        "<rootDir>/tests/jest.component.config.js"
    ]
}

This allowed me to run either jest on its own and it will run all projects or if I wanted to specify a specific config to run I could run jest --projects jest.unit.config.js and it will just run that specific project.

I could also add a scripts section to my package.json to run them more easily.

"scripts": {
    "test": "jest", 
    "test:unit": "jest --projects tests/jest.unit.config.js",
    "test:component": "jest --projects jest.component.config.js"
}

Upvotes: 3

mgarcia
mgarcia

Reputation: 6325

To specify different config files you can use the --config option.

For example if you have a tests/jest.config.js file configuration for your component tests and a jest.config.js file for your unit tests, you can configure the scripts in your package.json so that they look something like this:

"scripts": {
    "tests:unit": "jest --config=jest.config.js",
    "tests:component": "jest --config=tests/jest.config.js"
}

Upvotes: 15

Related Questions