Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I have a Vue.js application where two files contain:
import axios from "axios"
These files are located in src/lib within the application and include the import statement on their first line.
Running tests on Github causes Axios 1.0.0 to be installed, no matter what the package.json says, and now any test involving these files fails with the above error.
Changing the statement to
const axios = require("axios")
fails also; node_modules/axios/index.js contains an import statement on line 1 and the exception is thrown there.
A suggestion I've seen quite often for such issues is to add
"type": "module"
to package.json (which is at the same level as src/). This causes all tests to fail with a demand to rename vue.config.js as vue.config.cjs. Doing that gets me:
Error: You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously
, which I do not understand.
Can anyone suggest what to do here?
–
I was able to fix this error by forcing jest to import the commonjs axios build by adding
"jest": {
"moduleNameMapper": {
"axios": "axios/dist/node/axios.cjs"
to my package.json
. Other solutions using transformIgnorePatterns
didn't work for me.
–
–
–
–
The 1.x.x version of axios changed the module type from CommonJS to ECMAScript.
The 0.x.x version of axios index.js file
module.exports = require('./lib/axios');
The 1.x.x version of axiox index.js file
import axios from './lib/axios.js';
export default axios;
Basically, jest runs on Node.js environment, so it uses modules following the CommonJS.
If you want to use axios up to 1.x.x, you have to transpile the JavaScript module from ECMAScript type to CommonJS type.
Jest ignores /node_modules/
directory to transform basically.
https://jestjs.io/docs/27.x/configuration#transformignorepatterns-arraystring
So you have to override transformIgnorePatterns
option.
There are two ways to override transformIgnorePatterns
option.
jest.config.js
If your vue project uses jest.config.js
file, you add this option.
module.exports = {
preset: "@vue/cli-plugin-unit-jest",
transformIgnorePatterns: ["node_modules/(?!axios)"],
...other options
package.json
If your vue project uses package.json
file for jest, you add this option.
...other options
"jest": {
"preset": "@vue/cli-plugin-unit-jest",
"transformIgnorePatterns": ["node_modules\/(?!axios)"]
This regex can help you to transform axios module and ignore others under node_modules directory.
https://regexper.com/#node_modules%5C%2F%28%3F!axios%29
–
–
In my case I had to add the following line to the moduleNameMapper object in the jest config:
axios: '<rootDir>/node_modules/axios/dist/node/axios.cjs',
With NestJs if you are facing this issue, then upgrade your package.json with following package versions.
"jest": "^29.0.0"
"ts-jest": "^29.0.0"
I experience similar problem but the error is caused by jest
.
All the tests trying to import axios
fail and throw the same exception:
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:
/monorepo/node_modules/axios/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import axios from './lib/axios.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import { describe, expect, it } from '@jest/globals'
> 2 | import axios from 'axios'
The solution is simply tell jest
that axios
should be transformed with babel
:
const esModules = ['lodash-es', 'axios'].join('|')
# add these entries in module.exports
transform: {
[`^(${esModules}).+\\.js$`]: 'babel-jest',
transformIgnorePatterns: [`node_modules/(?!(${esModules}))`],
Note: I'm using Quasar Vue and this is their implementation.
–
Add moduleNameMapper in your jest.config.js
moduleNameMapper: {
axios: 'axios/dist/node/axios.cjs',
As an alternative approach when working with Jest and Typescript, you can mock the individual functions you require for your test:
import axios from 'axios'
jest.mock('axios', () => ({
post: jest.fn(),
get: jest.fn()
const mockedAxios = axios as jest.Mocked<typeof axios>
mockedAxios.post.mockResolvedValue({})
Although this approach worked for me, asking babel to transpile axios also did the trick:
// jest.config.js
module.exports = {
transformIgnorePatterns: [
'/node_modules/(?!(axios)/).*'
For Axios, add the following code to your package.json;
"jest": {
"transformIgnorePatterns": [
"/node_modules/(?!(axios)/)"
I faced with the same problem. And firstly used variant (inside package.json file):
"jest": {
"moduleNameMapper": {
"axios": "axios/dist/node/axios.cjs"
But for mocking I use axios-mock-adapter. And I got the error:
TypeError: mock.onGet is not a function
I changed code to:
"jest": {
"transformIgnorePatterns": [
"/node_modules/(?!(axios)/)"
And this solution works.
The versions:
"axios": "^1.4.0"
"axios-mock-adapter": "^1.21.5"
"@types/axios-mock-adapter": "^1.10.0"
Yarik Drago is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
try {
const response = await fetch("api/fruit/all",{method:"GET"});
const data = await response.json();
return data;
} catch (error) {
return error;
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.