Jest transformIgnorePatterns not working - javascript

I have spent a long time looking at other questions about this and looking at other projects on Github but none of the answers seem to work for me.
I am loading a third party library in my project, and when running Jest tests I get the error
export default portalCommunication;
^^^^^^
SyntaxError: Unexpected token export
> 1 | import portalCommunication from 'mathletics-portal-communication-service';
I have tried updating my Jest config in many ways to get it to transpile this library but I always get the same error.
This is my current jest.config.js file:
module.exports = {
moduleNameMapper: {
'\\.(css|scss)$': 'identity-obj-proxy',
'\\.svg$': '<rootDir>/test/mocks/svg-mock.js'
},
setupFiles: ['./test/test-setup.js'],
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!mathletics-portal-communication-service)'
]
};
I have also tried adding the transform property to run babel-jest against this mathletics-portal-communication-service directory.
Please help!

The transformIgnorePatterns didn't work for me until I changed my .babelrc to babel.config.js, like this:
module.exports = {
"presets": [
"#babel/preset-env"
]
};
as seen on this comment: https://github.com/facebook/jest/issues/6229#issuecomment-403539460

As a workaround for now I have changed my config to use the moduleNameMapper option to load a mock class for that library instead. I would have preferred to use transformIgnorePatterns instead so would still appreciate any ideas.
New config:
module.exports = {
moduleNameMapper: {
'\\.(css|scss)$': 'identity-obj-proxy',
'\\.svg$': '<rootDir>/test/mocks/svg-mock.js',
'mathletics-portal-communication-service': '<rootDir>/test/mocks/mathletics-portal-communication-service-mock.js'
},
setupFiles: ['./test/test-setup.js']
};

Another team at my org added some common module. This was not transpiled and so the issue.
I followed this: https://babeljs.io/docs/en/configuration#whats-your-use-case
Converted my .babelrc to babel.config.json
in jest config added this:
transformIgnorePatterns: ['/node_modules/(?!(#companyName)/).*/'],
This solved my problem.

Adding trailing slash fix this for me:
{
// ...
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!mathletics-portal-communication-service/)'
]
};

It might be your use of rootDir. Try:
"transformIgnorePatterns": [
"node_modules/(?!(mathletics-portal-communication-service))"
]

Related

Error: Unable to resolve module ... could not be found within the project or in these directories: node_modules

Error: Unable to resolve module navigation/stack-routes from /Users/jacksaunders/gymzoo/src/navigation/tabs/MainTabs.tsx: navigation/stack-routes could not be found within the project or in these directories:
node_modules
Hello there! I have just tried to set up absolute imports (using navigation/stack instead of ../../../navigation/stack)
I am not sure what is happening because it looks to be okay in my IDE but my metro is flagging the following error.
Here is my tsconfig for context:
I have tried deleting my node modules, npm i and pod install but theres no luck.
Please throw your suggestions at me! Or advise me on how to solve this.
All the best,
Jack :)
You need to update your babel.config.js to understand the root imports you're using here, because your .tsconfig only takes care about the code before it's transcompiled.
You can use the babel-plugin-root-import to achieve this.
npm package: https://www.npmjs.com/package/babel-plugin-root-import
Example babel.config.js could look like this:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'babel-plugin-root-import',
{
paths: [
{
rootPathSuffix: './src',
rootPathPrefix: 'src',
},
{
rootPathSuffix: './src/navigation',
rootPathPrefix: 'navigation',
},
]
},
],
],
};
It's not an only option though, you can also use babel-plugin-module-resolver, which is more popular (https://www.npmjs.com/package/babel-plugin-module-resolver).

How to use multiple Jest presets with only one Jest configuration file/setup?

A project I'm working on is already configured with Jest and testing works as it should. This is how the current jest.config.js file looks like;
const ignores = [...];
const coverageIgnores = [...];
module.exports = {
roots: ['<rootDir>/src'],
globals: {
'ts-jest': {
tsConfig: 'tsconfig.json',
},
},
moduleFileExtensions: ['js', 'json', 'ts'],
testPathIgnorePatterns: [...ignores],
coveragePathIgnorePatterns: [...ignores, ...coverageIgnores],
testEnvironment: 'node',
coverageThreshold: {
global: {
branches: 86,
functions: 75,
lines: 86,
statements: 86,
},
},
preset: 'ts-jest',
};
The configuration currently uses the ts-jest preset. The project also involves a DynamoDB instance that should be tested and that's where multiple presets come into play. The current preset, ts-jest, should be used in combination with the #shelf/jest-dynamodb-preset (https://jestjs.io/docs/en/dynamodb). The problem is that the preset property in the config is of type String and doesn't support an array or an object.
I've read some similar questions like this one; Is it possible to use Jest with multiple presets at the same time?, but questions like these don't seem to have a definitive working solution on how to solve this problem.
Others suggest a solution in which a separate Jest config is created for every preset, but this is something I don't want and that probably will cause more problems in the future.
It would be ideal to have this single config file modified to allow multiple (here 2) presets, but how can this be achieved?
You can't actually use two presets but since the preset for shelf/jest-dynamodb is just setting other options in the jest setup, you can call them yourself. I was able to do this by just adding to my "jest" section of package.json:
"globalSetup": "./node_modules/#shelf/jest-dynamodb/setup.js",
"globalTeardown": "./node_modules/#shelf/jest-dynamodb/teardown.js",
This makes the same calls that the preset was doing, meaning you can leave the preset to ts-jest
This is specific to the marriage of ts-jest and jest-dynamodb, but what worked for me was to change the jest config like this:
"jest": {
"preset": "#shelf/jest-dynamodb",
"transform": {
"^.+\\.tsx?$": [
"ts-jest",
{}
]
},
// ...
}

How can I transpile a dependency in node_modules with Nuxt 2?

I have read of issues with transpiling node_modules with Nuxt, but the new Nuxt 2 is said to have solved this with a transpile option in the nuxt.config.js file.
https://nuxtjs.org/api/configuration-build/#transpile
Here is what I have:
export default {
router: {
base: '/',
},
build: {
transpile: [
'choices.js',
'lazysizes',
'swiper',
'vee-validate'
],
extractCSS: true
},
srcDir: 'src/',
performance: {
gzip: true
},
render: {
compressor: {
threshold: 100
}
},
dev: false
}
I removed a few things that are unrelated to make it easier to read.
When I run npm run build (nuxt build) the compiled JS files contain references to es6 and es7 code such as const and let etc when it should be var.
I have isolated this issue to be coming from Swiper. It appears to internally depend on something called Dom7 that seems to be causing the problem.
I am wanting to compile these node_modules dependencies to es5 if possible. I'm not sure my current setup is actually doing anything at all in that regard.
I believe Nuxt uses vue-app for Babel, but I even tried the following to no success:
babel: {
presets: [
'#babel/preset-env'
],
plugins: [
'#babel/plugin-syntax-dynamic-import'
]
}
Not much joy there either. Nothing appears differently in the final build.
I am using Nuxt 2.1.0
Any help appreciated. Thanks!
You also need to transpile Dom7, so the Nuxt config should have:
build: {
transpile: [
'swiper',
'dom7',
],
}
I have the exact same issue.
The vendor option under build is deprecated, so it's simply ignored I believe from what I read here https://medium.com/nuxt/nuxt-2-is-coming-oh-yeah-212c1a9e1a67#a688
I managed to isolate my case to the "swiper" library. If I remove that from my project, all references to let, const or class are gone. I've tried the transpile option too, but it does not seem to have any effect.
Will you try to exclude swiper from your project to see if we can isolate the issue?

CSS module #import fails the Jest test suit

I am using Jest and Enzyme to test my application. I am getting error:
FAIL app/containers/Navbar/NavbarContainer.test.js
● Test suite failed to run
app/components/Navbar/styles.css: Unexpected token (1:0)
> 1 | #import "../../styles/base/_variables";
| ^
2 |
3 | .navbar{
4 | width: $navbar-width;
This is my Jest configuration in package.json:
"jest": {
"verbose": true,
"globals": {
"env": {
"isProd": false,
"isDev": true,
"command": "start"
}
},
"moduleNameMapper": {
"\\.(css)$": "identity-obj-proxy"
},
"moduleFileExtensions": [
"js",
"jsx",
"json",
"css"
],
"modulePaths": [
"/app"
],
"moduleDirectories": [
"node_modules"
],
"verbose": true,
"setupFiles": [
"./setupJest.js"
],
"setupTestFrameworkScriptFile": "<rootDir>/setupTests.js"
}
I was following the guides while setting up the application, and I found that identity-obj-proxy will help to mock css-modules functionality, but that's not working in my case. Please let me know what am I missing here.
P.S. this is about not ES6 modules import. The suit failed because there is a #import in css.
UPDATE who use create-react-app from feb 2018.
You cannot override the moduleNameMapper in package.json but in jest.config.js it works, unfortunately i havent found any docs about why it does the trick.
So my jest.config.js look like this:
module.exports = {
...,
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(scss|sass|css)$": "identity-obj-proxy"
}
}
and it skips scss files and #import quite well.
I added to devDependencies identity-obj-proxy
Backing my answer i followed jest webpack
So, I've found the solution to this problem. I was importing CSS without the extension in my components and Jest was confusing that import with JS file. Solution is instead of importing css like:
import * as styles from './styles'
you should import it like:
import * as styles from './styles.css'
One quick gotcha that I found with this. If you have a jest.config.js file, then you need to set your moduleNameWrapper inside of that config file.
I know this post is old but i solved this issue by adding jest-transform-css as a devDependency
npm i --save-dev jest-transform-css
and then adding the following inside jest.config.js
transform: {
'^.+\\.js$': 'babel-jest',
'.+\\.(css|styl|less|sass|scss)$': 'jest-transform-css'
}
you can refer to this github issue for more information

How do I move jest tests to a /test folder and get them to run?

edit: I'm pretty sure this question is out of date and Jest has changed since then. Don't assume the answers will work or even be relevant now.
Jest expects tests to be in _tests_ folder or to be named blah.test.js. I don't like either of those patterns. I want my test files to be in /test and naming them test/index.ios.test.js seems redundant and silly. My first stab at this is to change my jest config in package.json to be:
"jest": {
"testPathDirs": ["test"],
"testRegex": "\\.(js|jsx)$",
"preset": "react-native"
}
Which find the tests successfully but they all fail:
Cannot find module 'setupDevtools' from 'setup.js'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:151:17)
at Object.<anonymous> (node_modules/react-native/jest/setup.js:23:1)
That function is in node_modules/react-native/Libraries/Core/Devtools/setupDevtools.js. How do I tell Jest where to find it?
I solved the problem by just setting the regex so it finds all .js files in my ./test folder:
"jest": {
"preset": "react-native",
"globals": {
"__DEV__": true
},
"testRegex": "./test/.*.js$",
"rootDir": "."
},
(jcollum here: I don't know what __DEV__ is actually doing there but an error will be thrown if isn't. jest 17.0.3)
I think the best way to go about this is to configure testMatch. It defaults to:
[ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]
So you could either change __tests__ to tests or add a new entry into the array that checks for both. My use the following in my package.json:
"jest": {
"testMatch": [ "**/tests/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]
},
I think to set roots: ['<rootDir>/test/'] is simple way in jest.config.js
module.exports = {
roots: ['<rootDir>/test_unit/'],
...
}
It works well for me.

Categories

Resources