Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure different Jest testEnvironment for React Components and Backend API routes in NextJs?

NextJS supports Jest (with little configuration) along with React Testing library for testing frontend. We can also use Jest to test our backend code.

I am using a library in my API routes which relies on internal nodejs APIs. For them to work in the test environment, I need to set the jestConfig.testEnvironment to node.

For testing frontend React components, I need to set the jestConfig.testEnvironment to jest-environment-jsdom.

I know I can mock the backend library, but I want to emulate real environment without having to mock any library implementation.

One way I could think of was to use different file extensions for frontend (filename.frontend.test.ts) and backend (filename.backend.test.ts) tests. Then, I could create 2 different jest config files and specify the file extensions using the jestConfig.testMatch property in the respective config file. And I could then do the following in the npm scripts:

{
  "scripts": {
    "test:frontend": "jest --config jest.config.frontend.ts",
    "test:backend": "jest --config jest.config.backend.ts",
    "test": "npm-run-all test:*"
  }
}

I was wondering if there is a better way to do this?

I am using the following library versions:

  • next: 13+
  • jest: 29+
  • @testing-library/react: 13+
like image 868
vighnesh153 Avatar asked Dec 06 '25 20:12

vighnesh153


1 Answers

You may want to look into the projects field of the jest config.

https://jestjs.io/docs/configuration#projects-arraystring--projectconfig

Here's an example of running node and react tests in the same repo:

https://blog.jmtalarn.com/running-node-js-react-tests-same-project/

You can also add a doc-block at the top of tests to set the environment for that specific test:

/**
 * @jest-environment jsdom
 */
like image 198
adamperrry Avatar answered Dec 08 '25 10:12

adamperrry