I have an build file generated when the application is built/served, this build file doesn't exist when jest is run, although it works perfectly when serving the application. So I always receive the following error on jest:
Cannot find module 'dist/versioninfo' from
'../src/app.controller.ts'
Reproducible repository:
https://github.com/pedropapa/jest-issue
Just create an file "dist" and run "jest test". The file will exist in "dist" folder, but jest will throw an exception. I already tried the following solution, but it didn't work:
jest.mock(
'dist/versioninfo',
() => `
export const VERSAO = "0.0.1 (dev)";
export const DESCRICAO = "";
`,
);
Ok, digging around jest config I found the solution.
I just needed to change jest.rootDir to "." and include "jest.moduleNameMapper" to my package.json:
Before:
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
After:
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": ".",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node",
"moduleNameMapper": {
"^dist/(.*)$": "<rootDir>/dist/$1"
}
}
Related
So, I saw many similar issues, but most of them refer to built code, and this one is actually a CLI script.
My command is:
node_modules/.bin/babel-node -x .js,.jsx,.ts,.tsx scripts/database/index.ts generate
And if it calls some code from node_modules (React Native related to be precise) it will throw the error.
I tried type: module but it caused even worse errors.
babel.config.js:
module.exports = {
presets: [
'module:metro-react-native-babel-preset',
'#babel/preset-flow',
],
plugins: [
['#babel/plugin-proposal-decorators', { legacy: true }],
['#babel/plugin-transform-flow-strip-types'],
[
require.resolve('babel-plugin-module-resolver'),
{
root: ['.'],
extensions: [
'.ios.js',
'.android.js',
'.js',
'.ts',
'.tsx',
'.json',
// '.png',
],
alias: {
app: ['./app'],
'test/*': ['test/'],
'#components': './app/components',
},
},
],
],
sourceMaps: true,
};
tsconfig.json:
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"isolatedModules": true,
"jsx": "react",
"lib": ["ES2016"],
"module": "commonjs",
"moduleResolution": "node",
"noEmit": true,
"resolveJsonModule": true,
"strict": true,
"target": "esnext",
"baseUrl": "./",
"paths": {
"app/*": ["app/*"],
"tests": ["tests/*"],
},
// ensure ignores node_modules
"skipLibCheck": true,
"preserveSymlinks": true,
"typeRoots": ["./node_modules/#types"],
"types": [
"node",
"#wdio/types",
"webdriverio/async",
// "#wdio/jasmine-framework",
// "expect-webdriverio/jasmine",
"jest"
]
},
// "include": [
// "src/*",
// "tests/*",
// ],
"exclude": [
"node_modules",
"babel.config.js",
"metro.config.js",
"jest.config.js",
// isnores special cases
"**/modules/**",
"node_modules/react-native/**",
"node_modules/#react-navigation/**",
]
}
remove "type": "module"
install #babel/register
in your very first line of code, add this line
require('#babel/register')({ extensions: ['.js', '.jsx', '.ts', '.tsx'] })
npm script
"start": "babel-node -x js,.jsx,.ts,.tsx -- src/app.ts"
update:
turn out that you can skip the whole #babel/register thing, what you are missing is a -- in your command
Woof this was rough.
I recently started gradually adopting TS into my Node app and I thought that was the cause.
But I'm starting to think the default option for the --config in babel-node is no longer looking for babel.config.js and rather only looking for babel.config.json.
I painstakingly converted my babel config to JSON and that seems to have fixed.
Also, the --extensions argument must include .ts. So to support both .js and .ts files in the same project you need to define this:
package.json
"scripts": {
"task": "babel-node --extensions .js,.ts -- ",
}
babel.config.json
{
"presets": [
"#babel/preset-typescript",
[
"#babel/preset-env",
{
"targets": {
"node": "current"
}
}
]
],
"plugins": [
[
"module-resolver",
{
"root": ["./"],
"alias": {
"test": "./__test__"
}
}
]
]
}
Then finally I was able to execute CLI commands like so:
yarn task something.js
or
yarn task something.ts
I am trying to run jest from a runner with nestjs and node.js and got the following error
and did not manage to run a test with a custom alias
{ Error: Cannot find module '#app/core'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Module.load (internal/modules/cjs/loader.js:653:32) code: 'MODULE_NOT_FOUND' }
my jest-e2e.json that the jest run is configured as follows:
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": "..", // also tried '.'
"moduleNameMapper": {
"#app/(.*)": "<rootDir>/src/$1"
},
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
app/core is defined in the tsconfig.json as follows:
"paths": {
"*": ["types/*"],
"#app/*": ["*"]
}
and working well in unit testing with jest:
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"moduleNameMapper": {
"#app/(.*)": "<rootDir>/$1"
},
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
How can I get the moduleNameMapper to ignore the imports that are declared inside my node_modules directory?
I have a moduleNameMapper entry that looks for src/(.*) and translates it to <rootDir>/src/$1.
However, one of my dependencies (#sendgrid/mail) happens to use imports that start with ./src/ and they break when importing them into Jest.
The jest config:
module.exports = {
"testEnvironment": "node",
"collectCoverage": true,
"moduleFileExtensions": ["js", "json", "ts"],
"roots": ["src"],
"testRegex": ".spec.ts$",
"coverageDirectory": "../coverage",
"moduleDirectories": ["node_modules", "src"],
"clearMocks": true,
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"moduleNameMapper": {
"src/(.*)": "<rootDir>/src/$1"
},
"collectCoverageFrom": [
"**/*.{js,jsx,ts,tsx}",
"!**/*.entity.ts",
"!**/*.dto.ts",
"!**/*.module.ts"
]
}
Turns out instead of using moduleNameMapper to get src/* absolute imports to work you can just use the moduleDirectories option:
// jest.config.js
const path = require("path")
module.exports = {
"testEnvironment": "node",
"collectCoverage": true,
"moduleFileExtensions": ["js", "json", "ts"],
"roots": ["src"],
"testRegex": ".spec.ts$",
"coverageDirectory": "../coverage",
"moduleDirectories": ["node_modules", "src", __dirname], // <--- HERE!!!!
"clearMocks": true,
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.{js,jsx,ts,tsx}",
"!**/*.entity.ts",
"!**/*.dto.ts",
"!**/*.module.ts"
]
}
I building a boildplate for nestjs and microservices (still work in progress)
now i got an issue that i try to run the app or run the test and it give me this
the code located github link
the issue that on tsconfig.json i added paths
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist/apps",
"baseUrl": "./",
"incremental": true,
"paths": {
"#frontapi/*": ["./apps/front-api/src/*"],
"#config/*": ["./apps/config-server/src/*"],
"#entities/*": ["./apps/entities-server/src/*"],
"#devops/*": ["./apps/devops-mcu/src/*"],
"#tasks/*": ["./apps/task-que-handler/src/*"],
"#logicBus/*": ["./apps/logic-bus/src/*"],
"#common/*": ["./apps/common/*"]
}
},
"exclude": [
"node_modules",
"dist"
]
}
and i run the package json two of the commands for testing:
"start:frontapi": "npm run start:frontapi:env && tsc-watch -p tsconfig.build.json --onSuccess \"node -r tsconfig-paths/register -r ts-node/register --inspect-brk=5858 dist/front-api/src/main.js\"",
and
"test:e2e": "npm run clean&&tsc -p tsconfig.build.json && jest --config ./apps/front-api/test/jest-e2e.json",
and both give me that it dont located #common/config/configuration
and i have no idea what i have missing here and help with this one
Edit there is file called jest-e2e.json this his content
{
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"moduleNameMapper": {
"^#frontapi/(.*)$": "./apps/front-api/src/$1",
"^#config/(.*)$": "./apps/config-server/src/$1",
"^#entities/(.*)$": "./apps/entities-server/src/$1",
"^#devops/(.*)$": "./apps/devops-mcu/src/$1",
"^#tasks/(.*)$": "./apps/task-que-handler/src/$1",
"^#logicBus/(.*)$": "./apps/logic-bus/src/$1",
"^#common/(.*)$": "./apps/common/$1"
}
}
please let me know if i missing something here or you missing something will do my best to provide
I was facing the same issue.
After taking a look at your project structure, I have some suggestions/observations. I will focus on apps/front-api.
There you have the jest.e2e.json file inside the test directory
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
...,
"moduleNameMapper": {
"^#frontapi/(.*)$": "./apps/front-api/src/$1",
"^#config/(.*)$": "./apps/config-server/src/$1",
"^#entities/(.*)$": "./apps/entities-server/src/$1",
"^#devops/(.*)$": "./apps/devops-mcu/src/$1",
"^#tasks/(.*)$": "./apps/task-que-handler/src/$1",
"^#logicBus/(.*)$": "./apps/logic-bus/src/$1",
"^#common/(.*)$": "./apps/common/$1"
}
}
I'd like to point out that the rootDir: '.' makes reference to the directory the file is in, so in this case rootDir value will be /path/to/your/projectShowCase/backend/apps/front-api/test.
The important thing is that you can use relative paths in the moduleNameMapper. For instance:
"moduleNameMapper": {
"^#frontapi/(.*)$": "<rootDir>/../src/$1",
"^#config/(.*)$": "<rootDir>/../../config-server/src/$1",
...,
"^#common/(.*)$": "<rootDir>/../../common/$1"
}
You just need to map each dependency to its specific path
Version:11.10.0
OS:Ubuntu
Scope:Debugging testcases
Module: Zest Test Framework
IDE:VSCode
I'm trying to debug my test cases. All breakpoints in spec.ts file works. but breakpoints in src/folders, ie, controller files never works. VSCode shows them as a unverified breakpoints.
launch.json:
{
"type": "node",
"request": "launch",
"name": "Jest Tests",
"program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
"args": ["--runInBand","-i", "--config=${workspaceFolder}/jest.config.js"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"outFiles": [
"${workspaceRoot}/dist/**/*"
],
"envFile": "${workspaceRoot}/.env"
}
tsconfig.js:
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": false,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": false,
"allowJs": true /* Allow javascript files to be compiled. */,
"checkJs": false /* Report errors in .js files. */,
"sourceMap": true,
"outDir": "./dist",
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*",
"src/types/*"
]
},
"types": ["jest"]
},
"exclude": ["dist", "src/test"],
"include": [
"src"
],
"types": ["src/types"]
}
jest.config.js
module.exports = {
globals: {
'ts-jest': {
tsConfigFile: 'tsconfig.json'
}
},
moduleFileExtensions: [
'ts',
'js'
],
transform: {
'^.+\\.tsx?$': 'ts-jest',
'^.+\\.js$': 'babel-jest'
},
transformIgnorePatterns: ["[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"],
testMatch: [
'**/*.spec.ts'
],
testEnvironment: 'node',
testResultsProcessor: "jest-sonar-reporter",
coveragePathIgnorePatterns: [".*\\.d\\.ts"],
collectCoverageFrom: [
"src/**/**/*.{ts}",
"!src/index.ts"
]
};