Skip to content

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

Closed

Description

@craigmcc

I have several React applications created with a Typescript based create-react-app application (and using [email protected], which depends on [email protected]). 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 [email protected] 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]

Activity

  1. ddolcimascolo commented on Oct 6, 2022

    @ddolcimascolo

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

  2. dennybiasiolli commented on Oct 6, 2022

    @dennybiasiolli

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

    transformIgnorePatterns: ['/node_modules/(?!(axios)/)'],
  3. CSWITH89 commented on Oct 6, 2022

    @CSWITH89

    @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.

  4. dennybiasiolli commented on Oct 6, 2022

    @dennybiasiolli

    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 🥲

  5. craigmcc commented on Oct 7, 2022

    @craigmcc
    Author

    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.

  6. sharizard commented on Oct 7, 2022

    @sharizard

    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)/\"",

  7. yt-hzn commented on Oct 7, 2022

    @yt-hzn

    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

  8. visoft commented on Oct 7, 2022

    @visoft

    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)/)"
        ]
      },
  9. vitalyster commented on Oct 7, 2022

    @vitalyster

    Still an issue in 1.1.2

  10. pschyma commented on Oct 8, 2022

    @pschyma

    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.

  11. adrcrv commented on Oct 8, 2022

    @adrcrv

    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}
    }
  12. pzi commented on Oct 10, 2022

    @pzi

    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.

  13. KillerCodeMonkey commented on Oct 10, 2022

    @KillerCodeMonkey

    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

  14. JeffreyStevens commented on Oct 11, 2022

    @JeffreyStevens

    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?

  15. abelardolg commented on Oct 13, 2022

    @abelardolg

    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

  16. 71 remaining items

  17. ajdruff commented on Jun 29, 2023

    @ajdruff

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

    npm install [email protected]
    npm install [email protected]
    npm install [email protected]
    npm install [email protected]
    
  18. thereallukeguy commented on Aug 5, 2023

    @thereallukeguy

    This fixed it for me yarn remove axios

  19. craigmcc commented on Aug 5, 2023

    @craigmcc
    Author

    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.

  20. added a commit that references this issue on Sep 27, 2023
  21. adriandoinea commented on Oct 2, 2023

    @adriandoinea

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

  22. unandreshevia commented on Nov 11, 2023

    @unandreshevia

    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.

  23. hacker0limbo commented on May 7, 2024

    @hacker0limbo

    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"
        }
      },
    
  24. SwapnaliY16 commented on Jul 16, 2024

    @SwapnaliY16

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

    This is the only solution which worked for me! Thanks @hacker0limbo :)

  25. b0yblake commented on Jul 19, 2024

    @b0yblake

    I encountered the same error, and it turned into a nightmare. After debugging each package, I found this library to be the source of the issue.

    Suggestion: If you don't need the latest version, please downgrade to version 0.xx.
    (Till to 19/07/2024, at newest ver of axios, its still error. I try with Vite 5 and do the polyfill or custom inherits)

  26. conorheffron commented on Mar 10, 2025

    @conorheffron

    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)/\"",

    I have encountered this error on a personal project and this update to package.json works as a temporary fix, is there a recommended way to solve this issue already or planned?

    See pull request at conorheffron/ironoc#298

    Changes

    • Updates axios from 0.28.1 to 1.8.2
    • Workaround for existing Jest tests in react app to pass.
  27. self-assigned this
    on Jul 30, 2025
  28. added
    issue::bug
    on Mar 29, 2026
  29. jasonsaayman commented on Apr 24, 2026

    @jasonsaayman
    Member

    Please check the latest docs. This should no longer be the case, but if something is still amiss, please open an issue and tag me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

issue::bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions