Why does Jest fail with "Unexpected token *" on a simple import statement???
Error log:
Admin#Admin-PC MINGW32 /d/project (master)
$ npm run test
> MyApp#0.0.1 test D:\project
> jest
FAIL __tests__/App-test.tsx
? Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
D:\project\node_modules\react-navigation-tabs\src\navigators\createBottomTabNavigator.js:3
import * as React from 'react';
^
SyntaxError: Unexpected token *
14 | // );
15 |
> 16 | export default createBottomTabNavigator({
| ^
17 | map: {
18 | screen: MapView,
19 | navigationOptions: {
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:513:25)
at Object.get createBottomTabNavigator [as createBottomTabNavigator] (node_modules/react-navigation-tabs/src/index.js:9:12)
at Object.<anonymous> (src/app/main.view.tsx:16:16)
FAIL src/component/reinput/example/__tests__/index.ios.js (19.352s)
? Console
console.error node_modules/react-native/Libraries/YellowBox/YellowBox.js:59
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
? renders correctly
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
at invariant (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:55:15)
at createFiberFromTypeAndProps (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2054:11)
at createFiberFromElement (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2075:15)
at reconcileSingleElement (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:4605:23)
at reconcileChildFibers (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:4662:35)
at reconcileChildren (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6329:28)
at updateHostRoot (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6741:5)
at beginWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7566:14)
at performUnitOfWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11234:12)
at workLoop (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11266:24)
FAIL src/component/reinput/example/__tests__/index.android.js (19.365s)
? Console
console.error node_modules/react-native/Libraries/YellowBox/YellowBox.js:59
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
? renders correctly
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
at invariant (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:55:15)
at createFiberFromTypeAndProps (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2054:11)
at createFiberFromElement (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2075:15)
at reconcileSingleElement (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:4605:23)
at reconcileChildFibers (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:4662:35)
at reconcileChildren (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6329:28)
at updateHostRoot (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6741:5)
at beginWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7566:14)
at performUnitOfWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11234:12)
at workLoop (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11266:24)
Test Suites: 3 failed, 3 total
Tests: 2 failed, 2 total
Snapshots: 0 total
Time: 22.774s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! MyApp#0.0.1 test: `jest`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the MyApp#0.0.1 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Admin\AppData\Roaming\Roaming\npm-cache\_logs\2019-04-22T11_52_36_984Z-debug.log
package.json file:
{
"name": "MyApp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.8.3",
"react-native": "0.59.4",
"react-native-gesture-handler": "^1.1.0",
"react-native-reanimated": "^1.0.1",
"react-native-splash-screen": "^3.2.0",
"react-navigation": "^3.8.1",
"react-navigation-tabs": "^2.1.1"
},
"devDependencies": {
"#babel/core": "^7.4.3",
"#babel/runtime": "^7.4.3",
"#types/jest": "^24.0.11",
"#types/react": "^16.8.13",
"#types/react-dom": "^16.8.4",
"#types/react-native": "^0.57.46",
"#types/react-test-renderer": "^16.8.1",
"babel-jest": "^24.7.1",
"jest": "^24.7.1",
"metro-react-native-babel-preset": "^0.53.1",
"react-test-renderer": "16.8.3",
"typescript": "^3.4.3"
},
"jest": {
"preset": "react-native"
}
}
babel.config.js file:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
};
jest.config.js file:
module.exports = {
preset: 'react-native',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
}
Note: I am using react-native type-script template, like react-native init MyApp --template typescript
Some react-native libraries ship uncompiled ES6 code.
ES6 code needs to be compiled before it can be run by Jest.
The Jest doc about Testing React Native Apps includes a section about compiling dependencies that don't ship pre-compiled code.
You will need to tell Jest to compile react-navigation-tabs by whitelisting it in the transformIgnorePatterns option in your Jest config.
Example:
Changing the jest.config.js file into something like below, fixed the issue mentioned in OP.
But the react-native-reanimated module (which requires native integration) needs further work, and we should "Mock" modules with such native requirements (as described in another post).
module.exports = {
preset: 'react-native',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
transformIgnorePatterns: [
"node_modules/(?!(react-native"
+ "|react-navigation-tabs"
+ "|react-native-splash-screen"
+ "|react-native-screens"
+ "|react-native-reanimated"
+ ")/)",
],
}
Note that the transformIgnorePatterns option (which is an array of Regular-Expressions) is originally meant to exclude files from being compiled, but using (?!(some-dir-name|another-name)) pattern, with the "(?!...)" negative look-ahead, we do tell Jest to exclude anything in node_modules directory, except the names that we did specify.
As it has been said, some modules needs to be transpiled, & some don't.
Here is a regex I use that work in a lot of projects
"jest": {
"preset": "react-native",
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-(native|universal|navigation)-(.*)|#react-native-community/(.*)|#react-navigation/(.*)|bs-platform|(#[a-zA-Z]+/)?(bs|reason|rescript)-(.*)+)"
]
}
It's working for most common react native thing, & include also a specific package (here bs-platform) as an example, when isn't captured by previous patterns.
I had a similar issue on a React + Typescript app.
The first mistake I made was to define the jest.config.js as jest.config.ts
Running on Node v12.latest
Then the configuration that worked for me were the following:
// jest.config.js
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["./src"],
transform: { "\\.ts$": ["ts-jest"] },
testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
globals: {
"ts-jest": {
tsConfig: {
// allow js in typescript
allowJs: true,
},
},
},
};
// tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react",
"baseUrl": "."
},
"include": ["src"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
// package.json
"devDependencies": {
"#types/jest": "^26.0.5",
"jest": "^26.1.0",
"ts-jest": "^26.1.3"
}
If you're using not only React Native but also Expo, I fixed the same issue but for Expo components by following the official guide, Testing with Jest. Specifically, install via package manager the jest preset jest-expo, and then update my package.json as they describe:
"jest": {
"preset": "jest-expo",
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-clone-referenced-element|#react-native-community|expo(nent)?|#expo(nent)?/.*|react-navigation|#react-navigation/.*|#unimodules/.*|unimodules|sentry-expo|native-base|#sentry/.*)"
]
}
I also needed to add to the end of the transformIgnorePatterns regexp string an exception for |.*font.* as the Expo Fonts were what were giving me trouble. Probably I could have made it a bit more specific, but I hate regex, and this worked so I left it there!
Somewhere in your config file (.babelrc.js or package.json) you have to have "modules" under "presets" set to one of the "amd" | "umd" | "systemjs" | "commonjs" | "cjs" | "auto" | false.
referer this fragment from the documentation
something like this:
"presets": [
[
"#babel/preset-env", {
"targets": process.env.BABEL_TARGET === 'node' ? {
"node": 'current'
} : {
"browsers": [ "last 2 versions" ]
},
"loose": true,
"modules": 'commonjs'
}
]
]
I am using react-native-web and the fix for my issue was to add the react-native-web preset to my jest.config.js:
module.exports = {
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
timers: 'fake',
testPathIgnorePatterns: [
'<rootDir>/build/',
'<rootDir>/node_modules/',
'<rootDir>/rndemo/build/',
],
globals: {
'ts-jest': {
diagnostics: {
warnOnly: true,
},
},
},
preset: 'react-native-web',
}
modifying babel.config.js to below worked for me. Also presets should come first and then all other configs.
module.exports = {
presets: [['#babel/preset-env',{targets: {node:
'current',},loose:true,},],],
}
I'm still facing problems trying to use jest, typescript and es6 modules. My test are written in Typescript, I'm trying to import objects from js-file which uses es6 modules. To do that, I've followed jest documentation and have the following in my babel.config.js, which is located in project root:
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current'
}
}
]
]
};
I have the following dependencies installed:
"devDependencies": {
"#babel/core": "^7.2.2",
"#babel/preset-env": "^7.3.1",
"#types/jest": "^23.3.13",
"#types/node": "^10.12.18",
"babel-jest": "^24.1.0",
"jest": "^23.6.0",
"rollup": "^1.1.2",
"rollup-plugin-terser": "^4.0.4",
"rollup-plugin-typescript2": "^0.19.2",
"ts-jest": "^23.10.5",
"ts-node": "^8.0.1",
"typescript": "^3.2.4"
}
In jest.config.js I have the following:
module.exports = {
verbose: true,
transform: {
"^.+\\.jsx?$": "babel-jest",
'^.+\\.ts?$': 'ts-jest'
},
testEnvironment: 'node',
testRegex: '/test/.*\\.(test|spec)?\\.(ts|tsx)$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};
And finally, I'm trying to import like this in my tests:
import {Dag, Directions} from "../dist/dag";
And here it says: SyntaxError: Unexpected token export
D:\devel\tomtom_dag\dist\dag.js:72
}();export { e as Directions, t as Action, n as Dag };
Can someone say what am I doing wrong or point to the project with similar config? And yes, I've googled this already for several hours and have tried solutions from here, here and have tried with this plugin - with the same result=(
UPDATE:
I've created a project to reproduce the issue:
https://github.com/AntonPilyak/jest_typescript_es6
Also, I've noticed that I had forgot to mention that I was trying to use jest#23 version due to ts-jest can't work with the latest (gives a warning + I get an empty test suite). Maybe, my problems are coming out from that fact. But still, I'm unable to make a proper config: if I use the latest jest I get a warning + jest says that the test suite is empty and test is passing though it shouldn't.
It works with ts-jest 24 + it appears to be a bug in my IDE: https://youtrack.jetbrains.com/issue/IDEA-207553
I am getting this error when running a javascript file from inside using code runner.
(function (exports, require, module, __filename, __dirname) { import Vue from 'vue'
^^^
SyntaxError: Unexpected identifier
I do have a jsconfig.json file in the root of my project directory which includes
{
"compilerOptions": {
"target": "es6"
}
}
and my code runner configuration is simply
"code-runner.executorMap": {
"javascript": "node --no-warnings"
}
The only line of code in the test script is import Vue from 'vue'
How can i use es6 imports in vscode?
Take a look at this issue on GitHub. That issue references the solution to your problem. You probably have to use babel-register:
1:
$ npm i -D babel-register
2:
$ npm i -D babel-preset-es2015
3:
config babel in package.json
{
// ...
// something else
// ...
"devDependencies": {
"babel-preset-es2015": "^6.18.0",
"babel-register": "^6.18.0"
},
"babel": {
"presets": [
"es2015"
],
"sourceMaps": true,
"retainLines": true
}
}