Jest Vue failing: SyntaxError: Unexpected token 'export' - javascript

I have sucessfully setup Jest with Quasar and Vue and most of my tests work. The only test that is failing is this one because of the following error message
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:
/Users/kristijanstefanoski/Desktop/Projektt/Quasar/projektt/node_modules/capacitor-firebase-auth/dist/esm/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './definitions';
^^^^^^
SyntaxError: Unexpected token 'export'
> 1 | import * as auth from 'capacitor-firebase-auth';
| ^
2 | import * as firebase from "firebase";
3 | import store from '../store';
4 | import {set} from "src/mixins/storage";
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 Object.<anonymous> (src/mixins/auth.js:1:1)
I have already added the following in my jest config:
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!quasar/lang)',
'<rootDir>/node_modules/(?!capacitor-firebase-auth/)',
],
I also tried the following
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!quasar/lang)',
'<rootDir>/node_modules/(?!capacitor-firebase-auth/dist/esm/)',
],
But again without luck. Anything I might be missing?

Related

React Testing Causing Error "Cannot use import statement outside the module"

I was doing react testing for my redux based application where i wanted to test my redux middleware. in the middleware i used
import axios from "axios"
then it shows error that Cannot use import statement ouside a module
`
FAIL src/test/application/student.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:
/F/workspace/TahsinAyman/full-stack/student/frontend/node_modules/axios/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import axios from "axios";
| ^
2 | import application from "../../resources/application.json";
3 |
4 | axios.defaults.baseURL = application.backend;
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/main/service/student.js:1:1)
at Object.<anonymous> (src/main/service/service.js:1:1)
at Object.<anonymous> (src/test/application/student.test.js:3:1)
at TestScheduler.scheduleTests (node_modules/#jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/#jest/core/build/runJest.js:404:19)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 3.779 s
Ran all test suites.
`
I was expecting this to not show that error and simply run api request to my api. i tried to fix it but it was not working

test function is not recognized as a global function

I followed a JavaScript unit testing tutorial at acadamind.com in that tutorial instructor used Vitest for demonstrations and the reason they mentioned using Vitest instead of Jest was Jest needed some extra configuration to work with the latest JavaScript syntax.
After doing my own research about unit testing I realized industry demand unit testing skills with the Jest. So I followed another tutorial for learning unit testing with Jest and React Testing Library (RTL).
I created a brand new TypeScript project with Create React App (CRA) and followed the instructions in that tutorial and everything went well. The instructor mentioned that Jest and RTL are supported out of the box with CRA.
After studying unit testing I tried to apply that knowledge and write some tests with my application, which was created some time back, and recently we updated it to React Scripts 5. In that application, I check node_modules folder, and Jest is there as a dependency. But I have noticed that the following packages are not listed in the package.json file in my project, so I installed them:
#testing-library/jest-dom": "^5.16.5",
#testing-library/react": "^13.4.0",
#testing-library/user-event": "^14.4.3",
#types/jest": "^29.4.0",
After that, I noticed my new project has this file in the src folder so I have copy pasted this file as well.
setupTest.ts
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '#testing-library/jest-dom';
When I tried to run when I tried to write my first unit test I noticed that VS Code doesn't recognize this test function as a global function and indicates an error and then I try to run the test script and I am getting this error
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/pathum/Documents/tagd/node_modules/axios/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import axios from 'axios';
| ^
2 | // config
3 | import { HOST_API } from '../config';
4 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/utils/axios.ts:1:1)
at Object.<anonymous> (src/hooks/useRefresh.tsx:2:1)
at Object.<anonymous> (src/hooks/useAxiosPrivate.tsx:3:1)
at Object.<anonymous> (src/pages/contracts/contract-form/new-contact-person.tsx:12:1)
at Object.<anonymous> (src/pages/contracts/contract-form/parties.tsx:15:1)
at Object.<anonymous> (src/pages/contracts/contract-form/contract-form.tsx:9:1)
at Object.<anonymous> (src/pages/contracts/contract-form/contract-form.test.tsx:2:1)
at TestScheduler.scheduleTests (node_modules/#jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/#jest/core/build/runJest.js:404:19)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 2.398 s
Ran all test suites related to changed files.
Watch Usage: Press w to show more.
Seems I need to do some configurations for Jest to work properly in the application. How do I fix this?
Install the necessary dependencies: npm install --save-dev #babel/preset-typescript and npm install --save-dev jest-cli typescript
Create a new file in the root of your project called jest.config.js and add the following content to it:
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/*.test.ts'],
};
Add a new property called "jest" to the "scripts" section of your package.json file and set it to the following: "jest --config jest.config.js --coverage". This will tell Jest to use the configuration file you just created and also generate a coverage report.
Create a new file in the root of your project called tsconfig.test.json and add the following content to it:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./test-dist"
},
"include": [
"src/**/*.test.ts"
]
}
Finally, you can run your tests with npm run jest.
You also need to make sure that you are using import statement correctly in your tests. You should use import statement to import functions, classes, and variables from other modules, but you should use require statement to import modules that are not written in TypeScript.

Jest Import issue

I am importing some functions from the library which i have added as dependency but when I run test then jest is throwing error saying "jest encountered an unexpected token"
Below is the error details
Details:
C:\Users\sbhuyar\ami-ui-booking-analysis_angular\node_modules\#vana\ami-ui-authentication\src\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { USER_LOGGED_OUT_ERROR, DEV_ENV } from './constants';
^^^^^^
SyntaxError: Unexpected token 'export'
> 1 | import { initialize, login } from '#vana/ami-ui-authentication';
| ^
2 | const domainSuffix = '.travel-intelligence.com';
3 | export const DEV_ENV = '__dev__';
4 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/api/env.js:1:1)
FAIL src/app/login/loginController.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.

Jest encountered an unexpected token: unexpected token: {

I am having a problem running my Selenium tests with jest. Whenever I try to run the tests, it gives me the following error:
FAIL app/tests/master.selenium.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:
D:\Workspaces\Refrezh\frontend\internals\testing\enzyme-setup.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { configure } from "enzyme";
^
SyntaxError: Unexpected token {
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
This is weird as it suddenly stopped working and worked perfectly before.
Any thoughts?

Apollo react import not transpiled when running jest tests

I'm currently experimenting an issue with my new React project using React and GraphQL Apollo. Here is my stack :
Webpack to build/dev to project
Babel to transpile javascript/jsx files
Jest to run tests
Enzyme to test my react components
The issue: When I run my tests, it seems that Apollo react client is not transpiled and throw tests :
pp/containers/App/__tests__/App.test.jsx
● Test suite failed to run
/Users/utilisateur/Project/TrAVis/TrAVis/node_modules/react-apollo/graphql.js:19
import { Component, createElement } from 'react';
^^^^^^
SyntaxError: Unexpected token import
1 | import React, { Component } from 'react';
> 2 | import graphql from 'react-apollo/graphql';
3 | import { bool, object, shape } from 'prop-types';
4 |
5 | import getUserQuery from './query';
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:318:17)
at Object.<anonymous> (app/containers/App/App.jsx:2:16)
at Object.<anonymous> (app/containers/App/__tests__/App.test.jsx:4:12)
My jest configuration is :
module.exports = {
verbose: true,
moduleNameMapper: {
'\\.(css)$': 'identity-obj-proxy',
},
transform: {
'^.+\\.(js|jsx)$': 'babel-jest'
}
};
and my .babelrc is simply :
{
"presets": [
"react",
"es2015"
]
}
I found this issue https://github.com/facebook/jest/issues/3202 but it seems that the solution doesn't work with my project.
Can you help me?
Thank you,
SLedunois
You need to configure jest to handle es6 imports using babel-jest.
Add babel-jest to your project using the following command in your terminal.
npm install --save-dev jest babel-jest
In your jest.config.js file include the following under transform.
transform: {
"^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
},
Also make sure you are importing react-apollo correctly.
Currect version 2.1.9 at time of writing imports using the following syntax.
import { graphql } from 'react-apollo';
By default Jest won't transform the contents of your node_modules folder, where your installation of Apollo resides.
There is a config option for Jest, called transformIgnorePatterns that provides the ability to change this behavior in order to transform some of your dependencies present in node_modules.
In your case, you need to whitelist Apollo so that Jest transforms it before running your tests:
"transformIgnorePatterns": ["node_modules\/(?!(react-apollo))"]
What happens here is that Jest will ignore all the contents of node_modules except react-apollo, which will get transformed with Babel. That way you should stop seeing the error you are getting.

Categories

Resources