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:
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
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With