Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get jest to to work with ES6 dependencies

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.

like image 638
Robert Lemiesz Avatar asked Sep 13 '19 00:09

Robert Lemiesz


People also ask

Does Jest work with ES6?

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.

How does Jest recognize a test file?

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 .

Does Jest require node?

To read TypeScript configuration files Jest requires ts-node . Make sure it is installed in your project.


1 Answers

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)/)"
]
like image 59
Brian Adams Avatar answered Oct 05 '22 01:10

Brian Adams