Skip to content

Jest tests failed after upgrading axios to v1.1.2 #5101

Closed

Description

@imransilvake

Describe the bug

I updated the Axios from "axios": "^0.27.2" to "axios": "^1.1.2", and Jest tests are not working anymore with the following error:

FAIL src/app/slices/app/App.slice.test.tsx
  ● 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:

    /Users/imrankhan/Development/roc/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, { AxiosRequestConfig } from 'axios';
        | ^
      2 |
      3 | class HttpClientService {
      4 |       /**

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (src/app/services/http-client/HttpClient.service.tsx:1:1)

To Reproduce

  1. Use React and Axios latest version
  2. Create Jest test
  3. Run the test to generate the error

Environment

  • Axios Version ^v1.1.2
  • Browser Chrome
  • Browser Version Version 105.0.5195.125 (Official Build) (x86_64)
  • Node.js Version v18.4.0
  • OS: MAC OS 12.4
  • React: ^18.2.0

Temporary Fix

The following fix works for now but I expect a standard fix for this issue.

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

or

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

Activity

  1. lejahmie commented on Oct 11, 2022

    @lejahmie
    Contributor

    For context: Problem seem to be that Axios is now built as ES Module instead of CommonJs when not run in Node. Problem with Jest is that it runs code in Node, but application is built for web-clients.
    This is why telling Jest to transform Axios works.

  2. pzi commented on Oct 12, 2022

    @pzi

    See #5026

  3. rathpc commented on Oct 12, 2022

    @rathpc

    The change to transformIgnorePatterns does not work in my case so I am hoping there is a proper fix provided from axios soon.

  4. hisuwh commented on Oct 12, 2022

    @hisuwh

    yh transformIgnorePatterns "fix" is not working for me

  5. rathpc commented on Oct 12, 2022

    @rathpc

    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'),
      },
  6. rd-stefan-riehmer commented on Oct 14, 2022

    @rd-stefan-riehmer

    @rathpc - i tried your solution.
    outcome:
    jest test: mocking with jest.mock('axios') works again
    the app (called from jest): the library axios is imported and it's value is undefined and therefore i get an error => e.g. Cannot read properties of undefined (reading 'get')

  7. zntemel commented on Oct 22, 2022

    @zntemel

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

    this worked, when I restart test command

  8. otistruong commented on Oct 24, 2022

    @otistruong

    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'),
      },

    Thank you!
    This is work for me, not transformIgnorePatterns

  9. pzi commented on Oct 26, 2022

    @pzi

    Try upgrading jest to latest (>29.2.x), it worked for me without having to change jest config.

  10. single9 commented on Oct 28, 2022

    @single9

    Try upgrading jest to latest (>29.2.x), it worked for me without having to change jest config.

    You save my time!

  11. nskazki commented on Oct 29, 2022

    @nskazki

    Works for me:

    moduleNameMapper: {
        'axios': 'axios/dist/node/axios.cjs'
    }
    
  12. kurund commented on Nov 4, 2022

    @kurund

    Works for me:

    moduleNameMapper: {
        'axios': 'axios/dist/node/axios.cjs'
    }
    

    Thank you. This worked for me

  13. dhruvsakariya commented on Nov 6, 2022

    @dhruvsakariya

    Describe the bug

    I updated the Axios from "axios": "^0.27.2" to "axios": "^1.1.2", and Jest tests are not working anymore with the following error:

    FAIL src/app/slices/app/App.slice.test.tsx
      ● 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:
    
        /Users/imrankhan/Development/roc/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, { AxiosRequestConfig } from 'axios';
            | ^
          2 |
          3 | class HttpClientService {
          4 |       /**
    
          at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
          at Object.<anonymous> (src/app/services/http-client/HttpClient.service.tsx:1:1)
    

    To Reproduce

    1. Use React and Axios latest version
    2. Create Jest test
    3. Run the test to generate the error

    Environment

    • Axios Version ^v1.1.2
    • Browser Chrome
    • Browser Version Version 105.0.5195.125 (Official Build) (x86_64)
    • Node.js Version v18.4.0
    • OS: MAC OS 12.4
    • React: ^18.2.0

    Temporary Fix

    The following fix works for now but I expect a standard fix for this issue.

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

    or

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

    Thank You it worked

    Any permanent solution Found ??

  14. MatVD commented on Nov 8, 2022

    @MatVD

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

    Thanks... it works well for me

  15. 44 remaining items

  16. hems commented on Dec 2, 2023

    @hems

    --transformIgnorePatterns "node_modules/(?!axios)/""

    nothing suggested here or on the readme works for me as well..

    here are my versions:

    "jest": "^29.7.0",
    "nock": "^13.4.0",
    "axios": "^1.6.2",

    probably worth mentioning i'm using ts-node.. maybe has something to do with it?

  17. Namnika commented on Dec 14, 2023

    @Namnika

    In my case, I was also facing the same problem
    So I got to solve with this:

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

    That's why we moved to Vitest.

    but have one question jest can't work with Vite? Even knowing Vitest is integrated with jest, So still vitest should used?
    btw, I'm also using Vite

  18. SalahAdDin commented on Dec 15, 2023

    @SalahAdDin

    In my case, I was also facing the same problem So I got to solve with this:

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

    That's why we moved to Vitest.

    but have one question jest can't work with Vite? Even knowing Vitest is integrated with jest, So still vitest should used? btw, I'm also using Vite

    Forget Jest, embrace Vitest.

  19. devamitranjan commented on Dec 25, 2023

    @devamitranjan

    If you are using xhrAdapter then you have to use the module mapper configuration for the not found modules in your package.json file:

    "jest": { "moduleNameMapper": { "axios/unsafe/adapters/xhr": "axios/lib/adapters/xhr.js", "axios/unsafe/core/settle": "axios/lib/core/settle.js" } }

  20. YuraZakaryan commented on Mar 4, 2024

    @YuraZakaryan

    This is work for me
    "jest": { "moduleNameMapper": { "^axios$": "axios/dist/node/axios.cjs" } },

  21. markcorrea commented on Mar 13, 2024

    @markcorrea

    Solved for me for version 1.6.7. Inside jest-config.json:

    "moduleNameMapper": { "^axios$": "<rootDir>/node_modules/axios/dist/node/axios.cjs" },

  22. gclark-eightfold commented on May 14, 2024

    @gclark-eightfold

    To help anyone else in the future facing similar issues in other packages, I think the issue is that Jest 27 and below does not fully support package.json exports (see Jest 28 blog post)

    As for why this issue happens with Axios and not many other packages, axios is declaring "type": "module" in the package.json with "main": "index.js", such that index.js is an ESM file. If you are running jest tests in a non-node environment (e.g. jsdom), this will cause issues in Jest 27 and below since dist/node/axios.cjs is only referenced in the exports field.

    Solutions for Library Authors

    1. Make the main field in package.json references a CommonJS file and use the module field for the ESM file.
    2. Don't support Jest v27 and below out-of-the-box. (ideally also provide some docs regarding setup)
      • NOTE: If you are using the exports field to remap how consumers import specific entry points (e.g. my-package/hello-world -> my-package/dist/hello-world.cjs), not supporting Jest 27 and below may be the only option.

    Solutions for Application Authors

    1. Upgrade Jest to v28+ for package.json exports compatibility
    2. Use the moduleNameMapper config option to force the CJS file to be used. (See above examples for how this is done for axios specifically).
      • NOTE: Other recommendations above may also work, but this is the only one that I know of myself that works.
  23. added a commit that references this issue on Jul 23, 2024
  24. Russzh commented on Apr 16, 2025

    @Russzh

    jest: { configure: { collectCoverage: true, collectCoverageFrom: [ "src/**/*.{js,jsx,ts,tsx}", "!src/**/*.types.ts", "!src/**/*.d.ts", "!src/**/index.{js,jsx,ts,tsx}", "!src/reportWebVitals.ts", "!src/stories/*.{ts,tsx}", ], moduleNameMapper: { "^axios$": require.resolve("axios"), }, }, },

    in craco.config.js works for me

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions