jest cannot resolve module aliases - node.js

I am using a npm module called module-alias. I map some modules in tsconfig.json and package.json
tsconfig.json
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"#config/*": ["config/*"],
"#interfaces/*": ["interfaces/*"],
"#services/*": ["services/*"]
},
"module": "commonjs",
"target": "es2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"sourceMap": true,
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src",
"allowSyntheticDefaultImports": true /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
}
package.json
...
"_moduleAliases": {
"#config": "src/config",
"#interface": "src/interface",
"#services": "src/services"
},
"jest": {
"moduleNameMapper": {
"#config/(.*)": "src/config/$1",
"#interface/(.*)": "src/interface/$1",
"#services/(.*)": "src/services/$1"
},
"moduleFileExtensions": ['js', 'json', 'jsx', 'ts', 'tsx', 'node']
},
...
server.ts
import { logger } from '#config/logger';
everything works fine when I run npm start, but it gives me an error when I run jest
FAIL src/test/article.spec.ts
● Test suite failed to run
Cannot find module '#config/logger' from 'server.ts'
However, Jest was able to find:
'rest/server.ts'
You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'json', 'jsx', 'ts', 'tsx', 'node'].
Anyone know what the problem is? thanks
Solution works for me (Update 18/10/2019) :
Create a jest.config.js with code below:
module.exports = {
"roots": [
"<rootDir>/src/"
],
"transform": {
"^.+\\.tsx?$": "ts-jest"
}
}
and update moduleNameMapper in package.json:
...
"_moduleAliases": {
"#config": "./src/config",
"#interfaces": "./src/interfaces",
"#services": "./src/services"
},
"jest": {
"moduleNameMapper": {
"#config/(.*)": "<rootDir>/src/config/$1",
"#interfaces/(.*)": "<rootDir>/src/interfaces/$1",
"#services/(.*)": "<rootDir>/src/services/$1"
}
}
...

After a few hours I've managed to make this work. I'll try my best to simplify it to save others time and make it smooth.
My app is of the following stack:
Typescript (tsc and ts-node/register, no Babel) for the API build (.ts)
React (.tsx using Webpack)
jest for API testing (no Babel)
testcafe for UI/E2E
VSCode as IDE
Key notes:
The solution that works for me is must have "#" character in front of the alias. It's not required in theory by module-alias, however Jest is getting lost when we apply the module name mapper.
There needs to be consistency for naming between 'webpack' aliases and 'tsconfig'. It is necessary for VSCode not to red underline module names in TSX files.
This should work regardless of your document structure but remember to adapt baseUrl and jest config if encounter issues.
When applying changes in VSCode for .tsx files do not be worried that some of the paths are underlined. It's temporary as VSCode seems to grasp it only when all files are correctly connected to each other. It demotivated me at the start.
First, install module-alias from https://www.npmjs.com/package/module-alias with
npm i --save module-alias
then add to your initial startup file (for .ts files only, i.e. your application server):
require('module-alias/register')
as the module-alias docs indicate. Then setup tsconfig.ts. Keep it mind that baseUrl is relevant here as well:
{
"compilerOptions": {
"baseUrl": ".",
...
"paths": {
"#helpers/*": ["src/helpers/*"],
"#root/*": ["src/*"]
...
}
}
then setup your webpack.js:
const path = require('path')
...
{
resolve: {
...
alias: {
'#helpers': path.resolve(__dirname, 'src', 'helpers'),
'#root': path.resolve(__dirname, 'src')
}
}
}
then setup your package.json:
{
...
"_moduleAliases": {
"#helpers": "src/helpers",
"#root": "src"
}
}
then setup your jest config (I attach only things that were relevant when applying my change):
{
rootDir: ".",
roots: ["./src"],
transform: {
"^.+\\.ts?$": "ts-jest"
},
moduleNameMapper: {
"#helpers/(.*)": "<rootDir>/src/helpers/$1",
"#root/(.*)": "<rootDir>/src/$1"
},
...
}
Now, we need to take care of the build process because tsc is not capable of transpiling aliases to their relative siblings.
To do that we will use tscpaths package: https://github.com/joonhocho/tscpaths . This one is simple.
So considering your build command was just:
tsc
Now it becomes
tsc && tscpaths -p tsconfig.json -s ./src -o ./dist/server
You need to adjust your -s and -o to your structure, but when you inspect your .js file after build you should see if the relative path is correctly linked (and debug accordingly).
That's it. It should work as ace. It's a lot but it's worth it.
Example of a call in the controller (.ts) and in React component (.tsx) file:
import { IApiResponse } from '#intf/IApi'

In my case to support #Greg Wozniak's answer, I only needed to fix my jest config file.
My app uses jest.config.ts
In my src/index.ts I have import "module-alias/register"
In package.json:
{
...
"_moduleAliases": {
"#helpers": "dist/helpers",
"#root": "dist"
}
}
In tsconfig.json:
{
"compilerOptions": {
"baseUrl": "./src",
...
"paths": {
"#helpers/*": ["helpers/*"],
"#root/*": ["*"]
...
}
}
In jest.config.ts:
added roots, preset, the (.*) and $1 signs in moduleNameMapper*
{
roots: [
"<rootDir>/src/"
],
preset: "ts-jest",
transform: {
"^.+\\.(ts|tsx)$": "ts-jest",
},
moduleNameMapper: {
"#helpers/(.*)": "<rootDir>/src/helpers/$1",
"#root/(.*)": "<rootDir>/src/$1"
},
...
}

I think you don't have the routes properly configured in your tsconfig, since the paths lack the src folder (while they appear in your package.json module alias config):
Your tsconfig code:
"#config/*": ["config/*"],
"#interfaces/*": ["interfaces/*"],
"#services/*": ["services/*"]
How I think it should be:
"#config/*": ["src/config/*"],
"#interfaces/*": ["src/interfaces/*"],
"#services/*": ["src/services/*"]

Related

Mocking es6 with mocha in Typescript

I am struggling to properly stub/mock unit tests when using es6 modules along with a project with mixed .js and .ts files.
According to this post, testdouble should be able to provide the ESM mocking I need. However, it requires using --loader=testdouble to work, and I am currently using --loader=ts-node/esm. If I attempt to replace ts-node/esm, it is unable to find Typescript files:
Error [ERR_MODULE_NOT_FOUND]: Cannot find module
'/Users/repos/my-repo/src/models/connectionModel.js'
imported from
/Users/repos/my-repo/test/constants.tjs
(connectionModel is ts and imported as .js per esm convention)
Due to project requirements, I would need the project to be compiled in es6+, so removing type: module or setting module: cjs are not viable options for me.
Is there a viable way to use both loaders, or some other viable way to mock with es6?
package.json:
{
"type": "module",
"scripts": {
"test": mocha test/*.js test/*.spec.ts -r dotenv/config
}
}
tsconfig.json:
{
"compilerOptions": {
"target": "es2016",
"module": "es6,
"moduleResolution": "node16"
"allowJs": true,
"esModuleInterop": true
},
"ts-node": {
"esm": true
}
"include": [
"./src/**/*",
"test/**/*/.ts",
"test/**/*.js"
}
}
.mocharc.json: (grabbing from this answer)
{
"node-option": [
"experimental-specifier-resolution=node",
"loader=ts-node/esm"
]
}

Jest Typescript with ES Module in node_modules error - Must use import to load ES Module:

I'm trying to write a simple jest test for a 3rd party package were using that only exports an ES module. It's a wrapper around an http server.
Here is a test repo I setup (just run yarn && yarn jest to reproduce): https://github.com/jamesopti/hocuspocus-testing
No matter what config I experiment with, I still get this error when trying to run it:
Must use import to load ES Module: /Users/j/hocuspocus-testing/node_modules/#hocuspocus/server/dist/hocuspocus-server.esm.js
> 1 | import { Server, Hocuspocus } from '#hocuspocus/server'
| ^
2 | import * as request from 'supertest'
3 |
4 | describe('Server (e2e)', () => {
Things I've tried already:
The Jest instructions on ES modules: https://jestjs.io/docs/ecmascript-modules
In Jest configuration using transformIgnorePatterns
transformIgnorePatterns: ['node_modules/(?!#hocuspocus/)']
Using Babel via babel-jest
modifying transform setup in Jest configuration as '^.+\.jsx?$': 'babel-jest', '^.+\.tsx?$': 'ts-jest'
Ran into the error You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously.
Using .babel.config.js instead of .babelrc.js
Any ideas what I'm missing here? I thought this would be straightforward
[EDIT 1] - Added tsconfig.json and a working src/index.ts file to the example repo.
So for anyone still hitting this, ESM configuration explained in this section of documentation :
https://kulshekhar.github.io/ts-jest/docs/guides/esm-support
{
// [...]
"jest": {
"extensionsToTreatAsEsm": [".ts"],
"globals": {
"ts-jest": {
"useESM": true
}
}
}
}
JAN 2023: ES2022, TypeScript 4.9.4, jest 29.3.1, ts-jest 29.0.3
This is what worked for me, after 2 hours of frustration.
I used this configuration in jest.config.ts:
import type { JestConfigWithTsJest } from 'ts-jest'
const config: JestConfigWithTsJest = {
extensionsToTreatAsEsm: ['.ts'],
verbose: true,
preset: 'ts-jest/presets/default-esm',
testEnvironment: 'node',
transform: {
'^.+\\.(ts|tsx)?$': ['ts-jest', { useESM: true }]
},
testPathIgnorePatterns: ['./dist']
}
export default config
Change the test script in package.json to:
I use pnpm. Change to npx jest with npm,
or yarn exec with yarn
...
"scripts": {
...
"test": "NODE_OPTIONS=--experimental-vm-modules pnpm exec jest",
...
}
...
tsconfig.json:
{
"compilerOptions": {
"rootDirs": ["src"],
"outDir": "dist",
"lib": ["ES2022"],
"target": "ES2022",
"module": "ES2022",
"composite": true,
"moduleResolution": "node",
"declaration": true,
"declarationMap": true,
"incremental": true,
"esModuleInterop": true,
"types": ["jest", "node", "#types/jest"],
"sourceMap": true
},
"ts-node": {
"esm": true,
"experimentalSpecifierResolution": "node"
},
"include": ["./src/**/*", "./tests/**/*"]
}
See this (rather confusing) documentation for reference:
https://kulshekhar.github.io/ts-jest/docs/guides/esm-support/
You don't have a tsconfig.json file that specifies module. Therefore it uses the default, where it transpiles all your modules to CommonJS syntax, which uses require.
If you actually look at your dist/hocuspocus-server.esm.js, you should see it using require over the ESM import syntax.
I was having the same problem with my svelte app and testing. I ultimately traced it to having a jest.config.js and a jest.config.json in my root folder. It seems that jest does not have automatic config file resolution and was using a default configuration instead of either of my specified configurations.

Three.js with typescript autocomplete

I have a Node.js project that uses Typescript and Three.js. To import modules, I use the commonjs syntax, which I configured via
{
"compilerOptions": {
"module": "commonjs"
}
}
in my tsconfig.json. I downloaded Three.js via NPM have a typescript file like this:
const THREE = require('three');
const scene = new THREE.Scene();
which compiles fine, but I do not get any autocomplete. I don't think this specific to the editor used, as both Visual Studio Code as well as Neovim with YouCompleteMe don't work. Both work if I use the ES6 module syntax:
import * as THREE from 'node_modules/three/src/Three';
const scene = new THREE.Scene();
Here however I cannot get it to work without giving the actual path to the library (which is a problem later on when using webpack). What did I forget to configure to get autocomplete (or the ES6 syntax without explicitly defining the path, at this point I am fine with both solutions)?
EDIT
As mentioned in the comments to accepted answer, I was not able to find my mistake, but found a working solution while trying to create a minimal working project. So I will post this here, in case it might help someone else. If you have the same problem, please still read the answer, as it is correct.
My source file (in src/main.ts):
import * as THREE from 'three';
const scene = new THREE.Scene();
package.json (with webpack to test if the library can be resolved there):
{
"devDependencies": {
"#types/node": "^12.0.4",
"three": "^0.105.2",
"ts-loader": "^6.0.2",
"typescript": "^3.5.1",
"webpack": "^4.32.2",
"webpack-cli": "^3.3.2"
}
}
tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
"paths": { "*": ["types/*"] },
"target": "es6",
"module": "es6",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"sourceMap": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules/"
]
}
webpack.config.js:
const path = require('path');
module.exports = {
entry: './src/main.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
resolve: {
extensions: [ '.ts', '.js' ]
},
module: {
rules : [
{ test: /\.ts$/, use: [ 'ts-loader' ], exclude: /node_modules/ }
]
}
};
What version of three is installed in your package.json file? Make sure it's 0.101 or later, since that's when TypeScript support began. I recommend you use the latest (105 as of this writing), since it gets updated definition files on each release.
Then, in your .ts files, you can import it with:
import * as THREE from "three";
// After importing, THREE is available for auto-complete.
var lala = new THREE.WebGLRenderer();
Edit:
You might need to perform path-mapping in your .tsconfig file to force the compiler to find the correct module address. I've never had to do this, but the Typescript documentation suggests something like this:
{
"compilerOptions": {
"baseUrl": ".", // This must be specified if "paths" is.
"paths": {
"three": ["node_modules/three/src/Three"] // relative to "baseUrl"
}
}
}
Update r126
As of revision r126, Three.js has moved Typescript declaration files to a separate repository. If you're using r126 or later, you'll have to run npm install #types/three as a second step. Make sure you install the version of #types/three that targets your version of Three.js. For example:
"three": "0.129.0",
"#types/three": "^0.129.1",

importing class in Node js with typescript

I would import class in nodejs and use it in app.ts
var nano = require("nano");
import { EnvConfig } from './envConfig.service';
let config = new EnvConfig();
const dbCredentials: any = config.appEnv.getServiceCreds('dataservices');
export const nanodb = nano({
url: dbCredentials.url,
});
export const nanodbCockpitLight = nanodb.use('data');
console.log(dbCredentials);
When I try to compile I get this error.
import { EnvConfig } from './envConfig.service';
^
SyntaxError: Unexpected token {
I have created the tsconfig file :
{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"allowSyntheticDefaultImports": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"allowJs": true,
"outDir": "./dist",
//"baseUrl": "src" // Attention !! nécessite l'utilisation d'un loader de module node pour fonctionner sur node
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
I get this warning
No inputs were found in config file 'c:/Users/EHHD05911.COMMUN/Documents/cockpitLight/DB mananger/tsconfig.json'. Specified 'include' paths were '["src//"]' and 'exclude' paths were '["node_modules","/.spec.ts"]'
You cannot run node app.ts file directly that won't work
You need transpiler like babel js or typescript compiler tsc so first transpile to js file and then run node app.js
You're using .js extension, you need .ts extension, e.g.: app.ts instead of app.js.
Make sure you have typescript either in npm global or in dev dependencies.
I suspect whatever you're importing has typescript syntax (strong typing and such), and so running node directly won't work. You need to run tsc first, which will transpile everything to javascript in a dist folder, and then run node dist/app.js.
This is a bit cumbersome though, which is why there is ts-node. It's exactly what it sounds like, a node REPL for typescript. You should be able to run ts-node src/app.ts.
import { something } is a typescript syntax, it won't work in a .js file. That is a separate language. Try using require instead.
Use babel js which is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.
package.json
"dependencies": {
"#babel/polyfill": "^7.0.0",
}
"babel": {
"presets": [
"#babel/preset-env"
]
},
"scripts": {
"start": "server.js --exec babel-node",
}
https://babeljs.io/docs
This will enable/resolve your import statements.

Jest gives `Cannot find module` when importing components with absolute paths

Receiving the following error when running Jest
Cannot find module 'src/views/app' from 'index.jsx'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
at Object.<anonymous> (src/index.jsx:4:12)
index.jsx
import AppContainer from 'src/views/app';
package.json
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx,mjs}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
"<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
],
"moduleDirectories": [
"node_modules",
"src"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node",
"mjs"
]
},
My tests that run files that only contain relative paths in the tree run correctly.
To Clarify, I'm looking for how to configure Jest to not fail on absolute paths.
I think you're looking for: roots or modulePaths and moduleDirectories
You can add both relative and absolute paths.
I would make sure to include <rootDir> in the roots array, <rootDir> in the modulePaths array, and node_modules in the moduleDirectories array, unless you've got a good reason to exclude them.
"jest": {
"roots": [
"<rootDir>",
"/home/some/path/"
],
"modulePaths": [
"<rootDir>",
"/home/some/other/path"
],
"moduleDirectories": [
"node_modules"
],
}
Since in package.json you have:
"moduleDirectories": [
"node_modules",
"src"
]
Which says that each module you import will be looked into node_modules first and if not found will be looked into src directory.
Since it's looking into src directory you should use:
import AppContainer from 'views/app';
Please note that this path is absolute to the src directory, you do not have to navigate to locate it as relative path.
OR you can configure your root directory in moduleDirectories inside your pakcage.json so that all your components could be imported as you want it.
Adding
"moduleDirectories": [
"node_modules",
"src"
]
should work if you have Jest's config in your package.json file.
If you have a jest.config.js file, you should add it there, otherwise package.json will be overriden (and ignored) by this config file. So in your jest.config.js file:
module.exports = {
// ... lots of props
moduleDirectories: ["node_modules", "src"],
// ...
}
That's because jest doesn't recognize relative imports like src/views/app
Add a rootDir and a modulePaths in package.json
"name": "my-app",
...
"jest": {
...
"rootDir": "./",
"modulePaths": [
"<rootDir>"
],
...
}
}
Make sure you have run npm i or npm install after update the package.json. My issue was that :0
For those who are building something from scratch with Webpack and Babbel.
Try the following steps:
Delete the node_modules folder and install again. (This was something that solved my issue).
Here is a link with the necessary documentation to set up Webpack which in some cases will not be necessary. Jest Docs Webpack
Here is a link to the docs that explains how to set up Jest with React (Without using Create-React-App). Jest React Docs
4. Here is an example with a simple setup with Jest. You can set this up in package.json or the Jest configuration file.
Disclaimer: This does not answer the OP question. But most people will end up here for the keywords used for this issue.
"jest": {
"moduleFileExtensions": ["js", "jsx"],
"moduleDirectories": ["node_modules"],
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
}
},
In my case, I was running integration tests and all tests were in the same file with the path src/int-test.spec.ts in order to read paths I had to write:
"jest": {
...,
"moduleNameMapper": {
"src/(.*)": "<rootDir>/$1"
}
}
Adding __esModule:true fixed this issue for me.
jest.mock('module',()=>({
__esModule: true, // this makes it work
default: jest.fn()
}));
Hope this helps somebody. Although this is not very specific to the question.
This can also be caused by absolute imports present in the globalSetup file (or any files it references).
It seems like moduleNameMappers do not get applied to globalSetup files. I fixed this by just switching to relative imports for those specific files.
This Workaround:
Using "moduleNameMapper" in your jest configuration will make test-resolve work as expected:
"jest": {
"moduleNameMapper": {
"#(.*)": "<rootDir>/node_modules/$1"
}
}
https://gist.github.com/lydell/d62ce96c95c035811133a5396195da14
One of the modules I wanted to use has a .cjs extension.
Adding .cjs to moduleFileExtensions in jest.config.js fixed this problem for me.
My jest.config.js as example:
module.exports = {
moduleNameMapper: {
// see: https://github.com/kulshekhar/ts-jest/issues/414#issuecomment-517944368
"^#/(.*)$": "<rootDir>/src/$1",
},
preset: "ts-jest/presets/default-esm",
globals: {
"ts-jest": {
useESM: true,
},
},
testEnvironment: 'jsdom',
transform: {
'^.+\\.vue$': 'vue3-jest',
},
moduleFileExtensions: ['json', 'js', 'jsx', 'ts', 'tsx', 'vue', "cjs"],
moduleDirectories: ["node_modules"],
};
Just add "modulePaths" to your package.json
"jest": {
...
"modulePaths": [
"<rootDir>"
],
...
}
}
I had jest-expo installed, but not jest. Probably related that I'm prebuild-ejected from Expo. I had to run yarn add jest-expo jest to install jest, and updated jest-expo. Now my tests run.
Depending on your setup it might be, npm i jest-expo jest or expo install jest-expo jest. ... Got the idea from their docs https://docs.expo.dev/guides/testing-with-jest/

Resources