Jest React Native Expo.fx.js encountered an unexpected token - javascript

This is from the boilerplate Expo app built with create-react-native-app
Here's the jest section of my package.json:
"jest": {
"preset": "react-native",
"testEnvironment": "node"
},
Here's the output when I attempt to run jest:
> jest
FAIL src/__tests__/App.js
● 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:
/home/charney/om/star-harvester-centauri/node_modules/expo/build/Expo.fx.js:1
import './environment/react-native-logs.fx';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime._execModule (node_modules/jest-runtime/build/index.js:1157:58)
at Object.<anonymous> (node_modules/expo/src/Expo.ts:1:1)

Same answer as Jest encountered an unexpected token with react-native
"jest": {
"preset": "react-native",
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js" },
"testEnvironment": "node"
},

Related

Why isn't jest handling ES Module dependencies?

My package imports an ESM package called c2pa. When I run jest I get an error like this:
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• 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/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
I believe the docs for ECMAScript Modules are for if my package is ESM, but I am having an issue with a dependency.
I also updated my Jest config to try out transformIgnorePatterns override mentioned in the error and Jest gives an error: "SyntaxError: Unexpected token export".
const babelConfig = require('../../babel.config.json');
module.exports = {
preset: 'ts-jest/presets/js-with-babel',
testEnvironment: 'jsdom',
roots: ['tests', 'src'],
collectCoverageFrom: ['src/**/*.ts'],
coveragePathIgnorePatterns: ['__mocks__'],
moduleNameMapper: {
'^uxp$': '<rootDir>/../../dependency-mocks/uxp.js',
},
transformIgnorePatterns: ['/node_modules/(?!c2pa)/'],
globals: {
'ts-jest': {
babelConfig,
},
tsConfig: {
declaration: false,
},
PLUGIN_REV: '__pluginRev__',
},
setupFilesAfterEnv: ['./tests/test.setup.js'],
};
I also tried a babel plugin that is mentioned in the linked SO question.
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
},
I'm not sure if there's any other jest of babel config I might be missing here. Clearly something is wrong!
Aside from ignorePattern, I also updated preset:
preset: 'ts-jest/presets/js-with-ts',
The babel config changes were not necessary at all.

node-fetch 3.0.0 and jest gives SyntaxError: Cannot use import statement outside a module

I'm trying to upgrade my api to use node-fetch 3.0.0. Part of the breaking changes in their documentation is that node-fetch is now a pure ESM module.
https://github.com/node-fetch/node-fetch/blob/main/docs/CHANGELOG.md
My unit tests have started breaking from this change. I was using jest.requireActual("node-fetch") for the Response object
const { Response } = jest.requireActual("node-fetch");
However, with the new change, I get:
"Property 'Response' does not exist on type '{}'."
I tried changing to an import statement which seems to fix that error:
import { Response } from "node-fetch"
Now, I get the following error when I run my unit tests:
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:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• 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:
C:\Users\{mypath}\api\node_modules\node-fetch\src\index.js:9
import http from 'http';
^^^^^^
SyntaxError: Cannot use import statement outside a module
2 | import { AuthProvider, TokenCache } from "./tokenTypes";
3 | import { getUserEmail, getUserId, getUserRole } from "../common/authUtil";
> 4 | import fetch from "node-fetch";
The error seems to be occurring within node-fetch itself.
I tried changing the test script in my package.json to match what the jest documentation suggests for ESM modules. https://jestjs.io/docs/ecmascript-modules
package.json
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
The documentation also suggests changing the transform property in jest.config.js to take an empty object, but my transform object looks like the following for typescript and ts-jest:
jest.config.js
transform: { "^.+\\.ts?$": "ts-jest" }
If I change this to an empty object all of my tests break. I'm not very familiar with CJS vs ESM, so any help would be appreciated.
Fetch 3.0 is designed for using esmodules instead of commonjs. Therefore you have to make sure you import it into a module.
For example: to import it to app.js : Add "type":"module" in your package.json and then import it.
For importing it to other files or app.js even, you can also change the extension from .js to mjs that will tell nodejs to treat as a esmodule.
Otherwise downgrade fetch to use an older version that supports commonjs like 2.something.
npm install node-fetch#2
npm install #types/node-fetch#2
I had the same problem!
adding
transform: {
"^.+\\.(ts|tsx)$": "ts-jest",
"^.+\\.(js)$": "babel-jest",
},
transformIgnorePatterns: [
],
to my jest.config.js file solved it.
and btw these are my versions:
"jest": "^27.3.1",
"ts-jest": "^27.0.7",
"node-fetch": "^3.1.0"

"SyntaxError: Cannot use import statement outside a module" when importing a module which imports a module for side effects in Jest

I'm trying to use Jest to test some TS code I've written. I need this code to work on older browsers so am importing some polyfills and such for side effects.
My code looks something like this (variables changed to be more generic):
src/my_code.ts
import i18next from "i18next";
import Backend from 'i18next-http-backend';
import "promise-polyfill/src/polyfill";
var someVar = 12;
export function someFunc() {
return someVar + 1;
}
And my test looks something like this:
test/my_code.test.ts
import { someFunc } from '../src/my_code';
describe('some test case', function () {
console.log(someFunc());
});
I think my package.json and jest.config.js are okay, but running the test gives:
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• 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/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
my_code/node_modules/promise-polyfill/src/polyfill.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import Promise from './index';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import i18next from "i18next";
2 | import Backend from 'i18next-http-backend';
> 3 | import "promise-polyfill/src/polyfill";
| ^
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1479:14)
at Object.<anonymous> (src/my_code.ts:3:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.701 s
Ran all test suites.
npm ERR! Test failed. See above for more details.
The other modules I've imported in my source work, but these are using the import x from "y"; syntax rather than import "z"; for side effects.
Anything here I could try?
EDIT: Added jest.config.js below:
module.exports = {
transform: { '^.+\\.ts?$': 'ts-jest' },
testEnvironment: 'node',
testRegex: '/test/.*\\.(test|spec)?\\.(ts|tsx)$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};
Come on brotha, please show me yow jest.config file also yow app works with them import statements, bcuz there might be something bundling yow code up to a point it is understandable to the environment it runs, but on the other head you is running them tests files with nodejs and as you already see, node doesn’t understand that, plus adding the fact that them test cases are written in ts instead of js, try this first, if it doesn’t work I’ll need yow jest config.
Install ts-node.
If you want to execute some ts code ether you need yo compile them files first or you can install ts-node
npm i -D ts-node.
To run them tests you need ts-node ./path-to-yow-file.
I think there is already a package call ts-jest

Jest encountered an unexpected token with react + konva and/or react-konva

With Konva and react-konva installed and imported, my jest#enzyme tests failed to run with this error:
● 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".
Details:
C:\avius\fortest\node_modules\konva\lib\Core.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export { Konva } from './_CoreInternals.js';
^^^^^^
SyntaxError: Unexpected token 'export'
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (node_modules/react-konva/lib/ReactKonvaCore.js:19:13)
it is a newly created create-react-app for testing this error, so there is nothing special in it.
I have no babel.rc, nor babel.config.js or jest.config.js file. (because I tried a lot of setting, does not work.)
I can import and use other es6 modules like nanoid, lodash etc, so it seems that the konva needs something special? Uninstalling konva, everything working fine.
To get this to work I did the following:
I created a .babelrc containing the following:
{
"presets": [
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-transform-modules-commonjs"
]
}
This makes sure the files are in the correct format.
You will also have to install those packages.
I then put the following within my package.json file:
"jest": {
"testEnvironment":"jsdom",
"moduleNameMapper": {
"^konva": "konva/konva"
}
}
For good measure, I reinstalled all of my react-konva files (though that shouldn't have made a difference).
Extra:
If you get issues about not having certain variables defined make sure you have konva and canvas installed.
I was facing the same issue when I was using react-konva + react testing + react-jest-dom . What I observed , I got react-konva and react-jest-dom versions are not supporting each other. I uninstalled react-jest-dom and then again installed it. it worked for me. you can try this if the error is something like Jest encountered an unexpected token with react + konva and/or react-konva or export react-konva.
This happend to me while upgrading from react 16 to 17. this suggestion worked for me https://www.gitmemory.com/issue/konvajs/konva/1168/921810056
package.json
"jest": {
"moduleNameMapper": {
"^konva": "konva/konva"
}
}

JEST config testing node_module even if its disabled?

I am adding tests to existing codebase with Jest. This is the error I am getting
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:
/home/me/app/node_modules/register-service-worker/index.js:32
export function register (swUrl, hooks) {
^^^^^^
SyntaxError: Unexpected token export
I do not understand how to configure the transformIgnorePatterns properly?
But my jest.config.js is setup to ignore node_modules ?
Looking into the react example but can not really make sense how it translates to my stuff...? I'm in VueJS project, no typescript is used.
module.exports = {
preset: "#vue/cli-plugin-unit-jest/presets/typescript-and-babel",
moduleNameMapper: {
"^#/(.*)$": "<rootDir>/src/$1",
},
transformIgnorePatterns: ["/node_modules/"],
// setupFiles: [
// "./tests/unit/setup.ts",
// ],
};
It seems extending jest.config.js solved the error above.
"transform": {
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest",
"^.+\\.js$": "<rootDir>/node_modules/babel-jest"
},
I now have a different error, but this is more Vue specific now.

Categories