Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating Axios from 0.27.2 to 1.0.0 breaks Jest tests in a create-react-app app #5026

Open
craigmcc opened this issue Oct 6, 2022 · 80 comments

Comments

@craigmcc
Copy link

craigmcc commented Oct 6, 2022

I have several React applications created with a Typescript based create-react-app application (and using react-scripts@5.0.1, which depends on jest@27.4.3). Attempting to upgrade Axios from 0.27.2 to 1.0.0 causes Jest tests to fail with many errors like the one below. It appears that Axios@1.0.0 now emits only an ESM module, and no longer a CJS module, which causes known errors with Jest.

Test Runtime Error

/home/runner/work/library/library/client/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

   6 | // External Modules ----------------------------------------------------------
   7 |
>  8 | import axios, {AxiosInstance} from "axios";
     | ^
   9 |
  10 | // Internal Modules ----------------------------------------------------------
  11 |

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
  at Object.<anonymous> (src/clients/Api.ts:8:1)

Environment

  • Axios Version [1.0.0]
  • React Version [18.2.0]
  • React-Scripts Version [5.0.1]
  • Node.js Version [16.11.1]
  • OS: [OSX 12.6]
@ddolcimascolo
Copy link

Yes, hit by this too. I suppose adding an exclusion to transformIgnorePatterns would do it (not tested)

@dennybiasiolli
Copy link

dennybiasiolli commented Oct 6, 2022

@ddolcimascolo I can confirm, a temporary workaround is to add to jest.config.js

transformIgnorePatterns: ['/node_modules/(?!(axios)/)'],

@CSWITH89
Copy link

CSWITH89 commented Oct 6, 2022

@ddolcimascolo I can confirm, a temporary workaround is to add to jest.config.js

transformIgnorePatterns: ['/node_modules/(?!(axios)/)'],

Tried adding a jest.config.js with:

module.exports = {
  transformIgnorePatterns: ['/node_modules/(?!(axios)/)'],
};

And still encountering this error.

@dennybiasiolli
Copy link

In another project with vue 2.7 and pinia, I had already set this

  transformIgnorePatterns: [
    'node_modules/(vue-demi)',
  ],

and it's working with the new axios too...but I don't know why 🥲

@craigmcc
Copy link
Author

craigmcc commented Oct 7, 2022

Unfortunately, this still occurs with Axios 1.1.0 -- here's a link to a GitHub CI failure that illustrates the error:

https://github.com/cityteam/stats/actions/runs/3201927019/jobs/5230384125

I tried the suggestion about transformIgnorePatterns and it did not help either.

@sharizard
Copy link

The suggestion about transformIgnorePatterns in a jest.config.file didn't help me either. I also tried to add the transformIgnorePatterns using the jest key in my package.json without any success.

However, the tests started to run after I inlined the flag:

"test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\"",

@yt-hzn
Copy link

yt-hzn commented Oct 7, 2022

This is for those who are using next/jest like we are.

Adding transformIgnorePatterns: ['/node_modules/(?!(axios)/)'], in jest.config didn't help because it wasn't set due to how next/jest works. To be able to set transformIgnorePatterns using next/jest you can follow this and then the suggestion for adding transformIgnorePatterns will work

@visoft
Copy link

visoft commented Oct 7, 2022

This is still an issue with 1.1.2. I solved it by adding transformIgnorePatterns to my package.json. I also had to add react-native-daypicker to get that package to work with after upgrading axios jest:

  "jest": {
    "transformIgnorePatterns": [
      "/node_modules/(?!(axios|react-day-picker)/)"
    ]
  },

@vitalyster
Copy link

Still an issue in 1.1.2

@pschyma
Copy link

pschyma commented Oct 8, 2022

Same problem here with "react-date-picker. After upgrading to axios 1.1.2 and "fixing" the jest issue using "transformIgnorePatterns" the tests fail with jest complaining about date picker. Adding that module also to ignore patterns does not help and does not feel right as it's a not related package.

@adrcrv
Copy link

adrcrv commented Oct 8, 2022

This is for those who are using next/jest like we are.

Adding transformIgnorePatterns: ['/node_modules/(?!(axios)/)'], in jest.config didn't help because it wasn't set due to how next/jest works. To be able to set transformIgnorePatterns using next/jest you can follow this and then the suggestion for adding transformIgnorePatterns will work

@yt-hzn is right! Here is how i fixed it:

// jest.config.js file

const nextJest = require('next/jest');

const createJestConfig = nextJest({ dir: './' });

const customJestConfig = {
  // Custom Config Values
};

module.exports = async () => {
  const asyncConfig = createJestConfig(customJestConfig);
  const config = await asyncConfig();
  const transformIgnorePatterns = ["node_modules/(?!axios)/"]
  return {...config, transformIgnorePatterns}
}

@pzi
Copy link

pzi commented Oct 10, 2022

Note that

module.exports = async () => {
  const asyncConfig = createJestConfig(customJestConfig);
  const config = await asyncConfig();
  const transformIgnorePatterns = ["node_modules/(?!axios)/"]
  return {...config, transformIgnorePatterns}
}

will completely replace whatever you have in your custom jest config and also whatever comes from next jest. So if next/jest replaces/adds something it will be completely overwritten. The real issue is that next/jest adds node_modules as a hardcoded default which can be removed to resolve this issue, too:

module.exports = async () => {
  const asyncConfig = createJestConfig(customJestConfig);
  /** @type {import('@jest/types/build/Config').InitialOptions} */
  const config = await asyncConfig();

  const nodeModulePatternIndex = config.transformIgnorePatterns.findIndex(
    (pattern) => pattern === '/node_modules/'
  );
  if (nodeModulePatternIndex >= 0) {
    config.transformIgnorePatterns.splice(nodeModulePatternIndex, 1);
  }

  return config;
};

This makes it less of a breaking change going forward and allows to still have a complete jest config set up and all in one place.

@KillerCodeMonkey
Copy link

even excluding it from the transformIgnorePattern does not work for me... when i run the tests in testenv "jsdom" it tries to load the node-lib of axios where it seems that URLSearchParams does not exist

@JeffreyStevens
Copy link

JeffreyStevens commented Oct 11, 2022

I hit this issue as well, I use create react app and therefore the workaround is to add to the package.json jest property this way:

"jest": {
    "transform": {
        "^.+\\.[t|j]sx?$": "babel-jest"
    },
    "transformIgnorePatterns": ["<rootDir>/node_modules/(?!axios)/"],
}

However, this makes my Jest unit tests run about 2x longer. It would be nice if axios exported a module that supports Jest so we don't have to do this workaround?

@abelardolg
Copy link

abelardolg commented Oct 13, 2022

With all these lines, I received this error:
Error: You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously.
https://github.com/abelardolg/udemy_fherrera_vue3

@tada5hi
Copy link

tada5hi commented Oct 13, 2022

hope this is going to be fixed soon ...

@luutruong
Copy link

I have same issues with react-native project. Downgrade to 0.27.2 and fine. Hope this issue will be resolve soon.

@Guiqft
Copy link

Guiqft commented Oct 15, 2022

This works for me:

I found that this did however work for me because it forces those imports to resolve with the CJS module instead:

moduleNameMapper: {
    '^axios$': require.resolve('axios'),
},

ref: #5101 (comment)

@alumni
Copy link

alumni commented Oct 17, 2022

By the looks of it, 1.0.0+ is an ES module, so we can't use it in CommonJS projects.

@ElKlaus
Copy link

ElKlaus commented Mar 3, 2023

@ddolcimascolo I can confirm, a temporary workaround is to add to jest.config.js

transformIgnorePatterns: ['/node_modules/(?!(axios)/)'],

Thank you, it's work

@rlemasquerier
Copy link

For those for who transformIgnorePatterns is not working, make sure that your babel config is a js file (babel.config.js) instead of .babelrc.

Made the difference in my project, not sure why...

@MatGarreau
Copy link

@ddolcimascolo I can confirm, a temporary workaround is to add to jest.config.js

transformIgnorePatterns: ['/node_modules/(?!(axios)/)'],

Thank you, it's work

It works on my Vue3 project !
TY

@Veryinheart
Copy link

same issue with "jest": "^29.5.0", "axios": "^1.3.4" and None of these solutions works for me.

@dosolkowski-work
Copy link

Another odd data point: using axios@1.4.0 and jest@27 (due to create-react-app, although I tried manually upgrading to jest@29 and it didn't seem to affect this scenario), the transformIgnorePatterns solution worked with npm, but not after I switched to pnpm. The failure was not the usual "cannot use import statement", but rather some disconnect in the code that led to mocking not functioning, so axios was trying to make real HTTP requests when it should have been calling mocks. Maybe one thing was importing the module and the other CommonJS? I think the moduleNameMapper solution is likely to be "better" all else being equal.

@Tanmesh4
Copy link

Tanmesh4 commented May 9, 2023

This helped me

@kdreaming
Copy link

const axios = require('axios/dist/axios')
work for me

@RyanJSmillie
Copy link

This works for me:

I found that this did however work for me because it forces those imports to resolve with the CJS module instead:

moduleNameMapper: {
    '^axios$': require.resolve('axios'),
},

ref: #5101 (comment)

This addition to jest.config.js worked for me. Thanks!

@craigmcc
Copy link
Author

Given the amount of time that has gone on since my original bug report, and the fact that the only potential workarounds have all been just that -- workarounds (even in my experiments are only sketchily working for me) -- I'm giving up on Axios. The native Node and browser implementations of the fetch APIs have satisfied my requirements, without this kind of hassle, so it's time to reduce dependencies in my various apps. One app at a time.

FWIW, the React version I originally reported this for (18.2) is still current, which therefore means it will apply to anyone who uses Create React App (CRA) and even the current version of Axios (1.4), today.

Truth be told, this does make me a little sad ... Axios was the first HTTP API that worked well for me on both the client and server sides. But time marches on. And I cannot afford to be stuck in a world where there is (say) a security vulnerability in Axios 0.whatever, that is only fixed in Axios 1.whatever, which would mean invalidating a very large portion of my client side tests.

@xk08
Copy link

xk08 commented Jun 28, 2023

Just add

"jest": {
"transformIgnorePatterns": [
"/node_modules/(?!(axios)/)"
]
}

in package.json
and run npm install again works very well.

@craigmcc
Copy link
Author

Speaking just for myself, I do not want a workaround. I want the libraries I use to not break my tests when I “upgrade” the version, with no changes to my tests.

One might like to argue that the change from 0.x to 1.x is a “major” version change. Go for it. I do not care any more. Fetch does what I need, without an external dependency to worry about. Especially when it is over an issue of packaging, not even an API change.

@ajdruff
Copy link

ajdruff commented Jun 29, 2023

This fixed it for me after receiving the axios error after installing an aws library

npm install jest@29.5.0
npm install jest-mock@29.5.0
npm install ts-jest@29.1.0
npm install aws-sdk-v3-nest@0.2.0

@thereallukeguy
Copy link

This fixed it for me yarn remove axios

@craigmcc
Copy link
Author

craigmcc commented Aug 5, 2023

This fixed it for me yarn remove axios

Yah, that worked for me too (although I use npm instead of yarn :-).

It did require changing my client API calls to use the native fetch() APIs instead, but that was pretty straightforward since they were all concentrated in a set of modules encapsulating the server's API routes. Everything worked fine, including tweaking the middleware that passed along access tokens if the user was logged in.

rap1ds added a commit to sharetribe/flex-integration-sdk-js that referenced this issue Sep 27, 2023
The new axios version adds content-encoding gzip header.

Jest needs to be also updated. More info:
axios/axios#5026
@adriandoinea
Copy link

This is the only thing that worked for me
package.json
"transformIgnorePatterns": ["node_modules/(?!axios)/"]

@unandreshevia
Copy link

This works for me:

I found that this did however work for me because it forces those imports to resolve with the CJS module instead:

moduleNameMapper: {
    '^axios$': require.resolve('axios'),
},

ref: #5101 (comment)

I am pleased to report that the outcome was highly satisfactory with this solution.

@hacker0limbo
Copy link

Anyone who faced this problem and have tried transformIgnorePatterns but does not work like me, please try use moduleNameMapper instead referring to this answer: https://stackoverflow.com/a/74297004/12733140

  "jest": {
    "moduleNameMapper": {
      "^axios$": "axios/dist/node/axios.cjs"
    }
  },

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests