I am having issues using jest (specifically ts-jest) with path mapping. It's failing with the following error:
• Test suite failed to run
Configuration error:
Could not locate module @app/env.local.json mapped as:
./$1.
Please check your configuration for these entries:
{
"moduleNameMapper": {
"/^@app\/(.*)$/": "./$1"
},
"resolver": undefined
}
13 |
14 | // Utils / Types / Api
> 15 | import config from "@app/env.local.json"
| ^
16 |
17 | const URI_TO_DATABASE = "mongodb://localhost:27017/" + config.DATABASE_NAME
18 |
at createNoMappedModuleFoundError (node_modules/jest-resolve/build/resolver.js:577:17)
at Object.<anonymous> (database/database.ts:15:1)
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down. From __tests__/someTest.test.ts.
I believe my jest configuration is set up correctly:
const { pathsToModuleNameMapper } = require("ts-jest/utils")
const { compilerOptions } = require("./tsconfig.json")
module.exports = {
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths)
}
And here is my tsconfig settings:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"rootDir": ".",
"baseUrl": ".",
"paths": {
"@app/*": [
"./*"
],
"@api/*": [
"api/*"
],
"@database/*": [
"database/*"
],
"@pdf": [
"pdf/index.ts"
],
"@assets/*": [
"assets/*"
],
"@fonts": [
"assets/fonts/fonts.ts"
],
"@utils": [
"utils/*"
],
"@dbOperations": [
"database/dbOperations"
]
}
},
"include": [
"**/*.ts",
"jest.config.js"
],
"exclude": [
"node_modules"
]
}
I suspect that the error might be related to my project folder structure and ts config.
Currently, it maps @app/*
to ./*
(as per the error message), which seems correct. However, it's unable to locate the env configuration file.
My project directory looks like this:
|./
|-jest.config.js
|-tsconfig.json
|-moreFiles.ts
|-/database/
|--database.ts <-- imports `@app/env.local.json` and gets called anywhere in chain by jest tests
|-/__tests__/
|--someTest.test.ts
|-env.local.json
Any insights on how to resolve this issue? Your assistance is greatly appreciated, thank you :)