So I have a dependency package that I am pulling into my node_modules folder. This package has a export in it like this
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './client';
In order to get around this I use https://github.com/standard-things/esm. In my node loader
node -r esm index.js
.
However this does not work with my tests which are using Jest.
I cant seem to figure out how to just get Jest to transform these imports for me. I have tried so many things, and the current state of my configuration files is.
// babel.config.js
// babel.config.js
module.exports = {
presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript'],
plugins: ['@babel/plugin-transform-modules-commonjs'],
};
const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig');
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['<rootDir>/tests/**/*.{ts,js}'],
testPathIgnorePatterns: ['global.d.ts', 'utils.ts', '<rootDir>/node_modules/'], // tried with and without this
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' }),
};
Still keep getting that error. Anyone have a suggestion.
Jest can be used to mock ES6 classes that are imported into files you want to test. ES6 classes are constructor functions with some syntactic sugar. Therefore, any mock for an ES6 class must be a function or an actual ES6 class (which is, again, another function). So you can mock them using mock functions.
The pattern Jest uses to detect test files. By default it looks for . js and . jsx files inside of __tests__ folders, as well as any files with a suffix of .
To read TypeScript configuration files Jest requires ts-node . Make sure it is installed in your project.
transformIgnorePatterns
defaults to ["/node_modules/"]
which means that by default nothing in node_modules
gets transformed when Jest
runs.
If you have a dependency in node_modules
that needs to be transformed before running your unit tests then you will need to whitelist it with transformIgnorePatterns
in your Jest
config:
"transformIgnorePatterns": [
"node_modules/(?!(module-that-needs-to-be-transformed)/)"
]
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