Jest encountered an unexpected token - SyntaxError: Unexpected token 'export' - javascript

I'm using jest to test a react TypeScript app.
This is the test I'm running:
import { render, screen } from '#testing-library/react'
import { toBeInTheDocument } from '#testing-library/jest-dom'
import ContextProvider from '../../context/ContextProvider'
import { BrowserRouter } from 'react-router-dom'
import BlogPage from './BlogPage'
describe('BlogPage', () => {
test('Render blog page', () => {
render(
<ContextProvider>
<BrowserRouter>
<BlogPage/>
</BrowserRouter>
</ContextProvider>
)
expect(screen.getByText('In this page you can see some of the last articles I wrote.')).toBeInTheDocument()
})
})
And this is the error I'm getting:
FAIL src/components/blogPage/BlogPage.test.js
● Test suite failed to run
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
Details:
/home/German/Desktop/ger/code/projects/my-website/node_modules/react-markdown/index.js:6
export {uriTransformer} from './lib/uri-transformer.js'
^^^^^^
SyntaxError: Unexpected token 'export'
> 1 | import ReactMarkdown from 'react-markdown'
| ^
2 | import Accordion from 'react-bootstrap/Accordion'
3 |
4 | interface Props {
I understand this is because the library I'm using (react-markdown) doesn't have pre-compiled source code. The thing is I followed the docs (https://jestjs.io/docs/tutorial-react-native#transformignorepatterns-customization) and added the react-markdown folder to the transformIgnorePatterns config and I still get the error.
This is my jest.config.ts file:
import type { Config } from '#jest/types'
const config: Config.InitialOptions = {
verbose: true,
transform: {
'^.+\\.ts?$': 'ts-jest'
},
transformIgnorePatterns: [
'node_modules/(?!react-markdown/)'
]
}
export default config
I tried adding <rootDir> like <rootDir>/node_modules/(?!react-markdown/) and It didn't make a difference.
I also tried configuring jest directly from package.json instead of a jest.config file and It didn't make a difference either.
Then I found this question: Jest transformIgnorePatterns not working, which mentions you need to configure Babel.
I created my app with create-react-app so I didn't have Babel on my app. I installed it and created a babel.config.js file inside of which I put:
module.exports = {
"presets": [
"#babel/preset-env"
]
};
But I still get the error...
I'm running out of ideas. Any clue of how could I solve this?
Full code can be found here: https://github.com/coccagerman/my-website

react-markdown is shipped as js, add babel-jest as a transformer in your jest config
transform: {
'^.+\\.ts?$': 'ts-jest',
"^.+\\.(js|jsx)$": "babel-jest"
},

Related

jest Cannot find modules inside node_modules folder when using swc compiler (Next,js)

I have a project with Next.js and wanted to do some unit tests on it.
I followed the instruction provided here and managed to make some tests. it's also good to mention that I'm using the rust compiler and typescript for the project.
but there is an issue with one of the tests when loading a module from the node_modules folder. here is the output:
$ jest
info - Loaded env from /Projects/projectname/.env
PASS test/pages/index.test.tsx
PASS components/shared/ui/Button/Button.test.tsx
FAIL components/shared/ui/Card/Card.test.tsx
● Test suite failed to run
Cannot find module 'swiper/react' from 'components/attraction/Gallery/Gallery.tsx'
Require stack:
components/attraction/Gallery/Gallery.tsx
components/attraction/Gallery/index.ts
components/attraction/index.ts
components/index.ts
components/shared/ui/Card/Card.tsx
components/shared/ui/Card/Card.test.tsx
1 | import { IImageResponse } from '#/constants'
2 | import React, { useState } from 'react'
> 3 | import { Swiper, SwiperSlide } from 'swiper/react'
| ^
4 | import SwiperCore, { Pagination } from 'swiper'
5 | import styles from './Gallery.module.scss'
6 |
at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:324:11)
at Object.<anonymous> (components/attraction/Gallery/Gallery.tsx:3:51)
anything other than the components inside the project gives me this error.
here is the jest config for the project:
const nextJest = require('next/jest')
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
})
// Add any custom config to be passed to Jest
const customJestConfig = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleNameMapper: {
// Handle module aliases (this will be automatically configured for you soon)
'^#/(.*)$': '<rootDir>/$1',
},
testEnvironment: 'jest-environment-jsdom',
}
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig)
can anyone help as to why this is happening?

Jest - encountered an unexpected token when using transform property

I am not able to import Svg in my test, so I follow the answer here.
I've added this to jest.config.js
"transform": {
...
"^.+\\.svg$": "jest-svg-transformer"
}
After I've added it, error shows:
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
Details:
/Users/CCCC/Desktop/SourceTree/my-proj/src/setupTests.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { configure } from "enzyme";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/#jest/core/node_modules/jest-runtime/build/index.js:1728:14)
Anyone know why it fails?
jest.config.js
module.exports = {
moduleDirectories: ["node_modules", "src"],
moduleNameMapper: {
"^#/(.*)$": "<rootDir>/src/$1",
"\\.(css|scss)$": "identity-obj-proxy",
},
transform: {
"^.+\\.svg$": "<rootDir>/src/svgTransform.js",
},
setupFilesAfterEnv: ["<rootDir>/src/setupTests.js"],
snapshotSerializers: ["enzyme-to-json/serializer"],
};
setupTest.js
import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
configure({ adapter: new Adapter() });
After I install babel-jest and use it in transform, it works.
"transform": {
"^.+\\.js$": "babel-jest", // added this line
...
}
Reference:
How to resolve "Cannot use import statement outside a module" in jest

Configure jest with latest version of d3-path

For some reason, my jest configuration doesn't work with the latest version of d3-path#3.0.1. It worked fine with version 2.0.0. I guess it has something to do with d3-path switching to ESM, but I was already using ES6 in my own code, so I don't get why it suddenly doesn't work anymore. I have the following packages installed:
"dependencies": {
"d3-path": "^3.0.1"
},
"devDependencies": {
"#babel/core": "^7.15.8",
"#babel/preset-env": "^7.15.8",
"babel-jest": "^27.3.1",
"jest": "^27.3.1"
}
My babel.config.js:
module.exports = {
presets: [['#babel/preset-env', {targets: {node: 'current'}}]],
};
My index.js:
import { path } from 'd3-path'
export default () => path()
The test file:
import fn from '../src/index.js'
describe('test', () => {
it('works', () => {
fn()
expect(2 + 2).toBe(4)
})
})
The error message:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export {default as path} from "./path.js";
^^^^^^
SyntaxError: Unexpected token 'export'
> 1 | import { path } from 'd3-path'
To reproduce:
git clone https://github.com/luucvanderzee/jest-problem.git
cd jest-problem
npm i
npm run test
// The test runs without failure- this is because we're currently still using d3-path#2.0.0
npm uninstall d3-path && npm install d3-path // (upgrade to d3-path#3.0.1)
npm run test
// Now the test fails.
How should I configure jest and/or babel to solve this issue?
EDIT:
I already tried the following (from this page of the jest docs):
Creating a jest.config.js file with the following:
module.exports = {
transform: {}
}
Changing my "test" command from "jest" to "node --experimental-vm-modules node_modules/jest/bin/jest.js"
This gives me another error:
/home/luuc/Projects/javascript/jest-problem/test/test.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import fn from '../src/index.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
I also don't get what is meant by
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
Isn't the problem that the module is not transformed? Would adding an ignore pattern not just lead to the module not getting transformed?
Problem
The error happens because jest does not send the content of node_modules to be transformed by babel by default.
The following output line of npm run test indicates one way to solve the problem:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
Solution
The configuration of jest should be updated in order to instruct it to transform the ESM code present in d3-path dependency.
To do so, add the following to a jest.config.js file in the root directory of the project:
module.exports = {
transformIgnorePatterns: ['node_modules/(?!(d3-path)/)']
}
npm run test runs fine after that.
The transformIgnorePatterns option is documented here.
Edit - including more modules
In order to include all modules starting with d3, the following syntax may be used:
transformIgnorePatterns: ['/node_modules/(?!(d3.*)/)']
TLDR;
transformIgnorePatterns: [
"/node_modules/(?!d3|d3-array|d3-axis|d3-brush|d3-chord|d3-color|d3-contour|d3-delaunay|d3-dispatch|d3-drag|d3-dsv|d3-ease|d3-fetch|d3-force|d3-format|d3-geo|d3-hierarchy|d3-interpolate|d3-path|d3-polygon|d3-quadtree|d3-random|d3-scale|d3-scale-chromatic|d3-selection|d3-shape|d3-time|d3-time-format|d3-timer|d3-transition|d3-zoom}|internmap|d3-delaunay|delaunator|robust-predicates)"
]
For the ones reaching this page after updating recharts dependency, here I found the solution, provided by them.

"SyntaxError: Cannot use import statement outside a module" when running a Jest test with Vue Js

I followed this tutorial https://frontstuff.io/build-your-first-vue-js-component to build a vue js component.
I then followed this tutorial https://frontstuff.io/unit-test-your-first-vuejs-component to unit test the component.
The unit test fails at the import statement on the component and returns this error:
● Test suite failed to run
C:\Users\SHINIGAMI-ALFSABAH\Documents\Workspace\Dev\Vue\star-rating\node_modules\vue-awesome\icons\star.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Icon from '../components/Icon.vue'
^^^^^^
SyntaxError: Cannot use import statement outside a module
12 |
13 | <script>
> 14 | import 'vue-awesome/icons/star'
| ^
15 | import Icon from 'vue-awesome/components/Icon'
16 |
17 | export default {
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
at src/components/Rating.vue:14:1
at Object.<anonymous> (src/components/Rating.vue:67:3)
Any help will be appreciated.
I found an answer on SO from a previous similar question Unexpected token 'import' error while running Jest tests?
Basically I had to change my transformIgnorePatterns array in my jest config from:
transformIgnorePatterns: ["/node_modules/"],
to
transformIgnorePatterns: ["/node_modules/(?!vue-awesome)"],
making sure jest compiles 'vue-awesome' module to use in the test.
What I did was I installed the dependencies needed for vue and jest to work together, then I created a config file for babel and jest.
//Installing dependencies for jest and vue js
npm i -D #vue/test-utils jest vue-jest #vue/babel-preset-app babel-core#^7.0.0-bridge.0
//jest.config.js
module.exports = {
moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
transform: {
".*\\.(vue)$": "vue-jest",
"^.+\\.js$": "<rootDir>/node_modules/babel-jest"
}
};
//babel.config.js
module.exports = {
presets: [
'#vue/app'
]
};
For me, it was a missing name: field in the components that it was having trouble with, and then clearing the jest cache.

Jest - Jest encountered an unexpected token. Vanilla JS

I'm trying to make a complex zip extractor in JavaScript and I decided that unit testing would be very important. That being said, a friend recommended Jest. I couldn't get any of my tests to work so I made a dumb test that made sure the first value of my JS Enum is 0. Jest, however, fails ever time saying that it encountered an unexpected token
I tried a more complex test and simplified it down to this simple test:
enums.js:
const Format = {
UNKNOWN: 0,
ZIP: 1,
TAR_GZIP: 2,
TAR_BZIP: 3,
};
export default Format
enums.test.js
const {Format} = require("../src/enums.js");
test("bad test", () => {
expect(Format.UNKNOWN).toBe(0);
});
The error that is gives me is this:
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/giovanni/WebstormProjects/extract.js/src/enums.js:7
export default Format;
^^^^^^
SyntaxError: Unexpected token export
> 1 | const Format = require("../src/enums.js");
| ^
2 |
3 | test("bad test", () => {
4 | expect(Format.UNKNOWN).toBe(0);
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.<anonymous> (test/enum.test.js:1:1)
Using Bable fixed this. Once I installed Babel with NPM, I added a file .babelrc with the contents:
{
"presets": ["#babel/preset-env"]
}
This worked.

Categories

Resources