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

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

Closed
imransilvake opened this issue Oct 11, 2022 · 38 comments
Closed

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

imransilvake opened this issue Oct 11, 2022 · 38 comments

Comments

@imransilvake
Copy link

imransilvake commented Oct 11, 2022

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)/\"",
@lejahmie
Copy link
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.

@pzi
Copy link

pzi commented Oct 12, 2022

See #5026

@rathpc
Copy link

rathpc commented Oct 12, 2022

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

@hisuwh
Copy link

hisuwh commented Oct 12, 2022

yh transformIgnorePatterns "fix" is not working for me

@rathpc
Copy link

rathpc commented Oct 12, 2022

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

@rd-stefan-riehmer
Copy link

@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')

@zntemel
Copy link

zntemel commented Oct 22, 2022

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

this worked, when I restart test command

@tanthuann
Copy link

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

@pzi
Copy link

pzi commented Oct 26, 2022

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

@single9
Copy link

single9 commented Oct 28, 2022

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

You save my time!

@nskazki
Copy link

nskazki commented Oct 29, 2022

Works for me:

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

gsreynolds added a commit to giranm/pd-live-react that referenced this issue Nov 2, 2022
…eNameMapper to workaround

axios/axios#5101
Signed-off-by: Gavin Reynolds <greynolds@pagerduty.com>
@kurund
Copy link

kurund commented Nov 4, 2022

Works for me:

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

Thank you. This worked for me

@dhruvsakariya
Copy link

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 ??

@MatVD
Copy link

MatVD commented Nov 8, 2022

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

Thanks... it works well for me

@dhruvsakariya
Copy link

dhruvsakariya commented Nov 8, 2022 via email

@AyoubXwire
Copy link

AyoubXwire commented Nov 8, 2022

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

You can also do it this way:
add this jest config to your package.json

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

and you can keep the npm test script as it was before:
"test": "react-scripts test",

@jasonsaayman
Copy link
Member

Hi 👋

Please try the latest pre-release by running the following:

npm i axios@1.2.0-alpha.1

Please provide feedback in either the pinned issue or the discussion thread 🧵

@OVO-Josh
Copy link

@KonradLinkowski oh whoops 😅. Yeah we should probably have one of them opened

@ventralnet
Copy link

ventralnet commented Dec 20, 2022

Just leaving this here. Here is a blurb from the JEST documentation why you have to include axios in transforming/transpiling. By default JEST ignores node_modules/*

Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled code. Since all files inside node_modules are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors. To overcome this, you may use transformIgnorePatterns to allow transpiling such modules. You'll find a good example of this use case in React Native Guide.

@ventralnet
Copy link

Yet further useful information why Jest is transpiling
https://jestjs.io/docs/code-transformation

@77pintu
Copy link

77pintu commented Dec 29, 2022

Finally, the issue is resolved I updated the latest jest version --->npm install --save-dev jest@29.3.1

another way this also working
"test": "react-scripts test --transformIgnorePatterns "node_modules/(?!axios)/""

this worked when I restarted the test command

SpiritBreaker226 added a commit to SpiritBreaker226/portfolio that referenced this issue Dec 30, 2022
Add the Axios package to connect to the API so we can get data from the
'dev.to' API. Currently, the latest version of Axios, v1.1.2, does not
work with Jest, so we are staying with v0.27.2.

Ref:

https://axios-http.com
axios/axios#5101 (comment)
SpiritBreaker226 added a commit to SpiritBreaker226/portfolio that referenced this issue Dec 30, 2022
Add the Axios package to connect to the API so we can get data from the
'dev.to' API. Currently, the latest version of Axios, v1.1.2, does not
work with Jest, so we are staying with v0.27.2.

Ref:

https://axios-http.com
axios/axios#5101 (comment)
@LiviuSosu
Copy link

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

Up from me ;-)

holly-cummins added a commit to holly-cummins/house-of-microservices-quarkus-contract-testing-sample that referenced this issue Jan 24, 2023
…e in axios/axios#5101, then update pact to fix pact-foundation/pact-js#606, and move dev dependencies to dev scope.
@SalahAdDin
Copy link

No any of the solutions given here gave us a proper solution, we are working with the 1.2.5 version.

rolandgeider added a commit to wger-project/react that referenced this issue Jan 30, 2023
ramontayag added a commit to swan-bitcoin/node-marketo that referenced this issue Feb 1, 2023
Versions of Axios 1.x are causing issues with
Jest (axios/axios#5101).

Jest 28 and 29, where this issue is resolved, has other
issues surrounding memory leaks
(jestjs/jest#7874).

Allow `>=0.25.0` for applications that cannot upgrade Jest
at this moment.
@imransilvake
Copy link
Author

imransilvake commented Feb 6, 2023

Checked on "axios": "^1.3.2" still not fixed (without --transformIgnorePatterns) !!

@arpitha-jaanaki
Copy link

HI @imransilvake did u not faced error like "options must be an object error" with latest version of axios?

AXIOS VERSION used

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

axiosservice.js file looks like below

import axios from 'axios';
import { qs, parse, stringify } from 'qs';
const buildInfoFilePath = '/system/buildInfo.json';

class AxiosService {
instance = axios.create({
paramsSerializer: {
encode: parse,
serialize: stringify
}
});

none of the solution worked for me .

can u please guide me what exactly fixed your issue, and how your axios service.js file looks like

Advance
thanks

@imransilvake
Copy link
Author

imransilvake commented Feb 12, 2023

HI @imransilvake did u not faced error like "options must be an object error" with latest version of axios?

AXIOS VERSION used

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

axiosservice.js file looks like below

import axios from 'axios'; import { qs, parse, stringify } from 'qs'; const buildInfoFilePath = '/system/buildInfo.json';

class AxiosService { instance = axios.create({ paramsSerializer: { encode: parse, serialize: stringify } });

none of the solution worked for me .

can u please guide me what exactly fixed your issue, and how your axios service.js file looks like

Advance thanks

No, I didn't.
My axios service contains get, put, post and delete methods such as:

	/**
	 * GET
	 * @param url
	 * @param config
	 */
	get = async <T>(url: string, config?: AxiosRequestConfig): Promise<T> => {
		const resp = await axios.get(url, config);
		return resp.data as T;
	};

that worked for me:

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

@SalahAdDin
Copy link

HI @imransilvake did u not faced error like "options must be an object error" with latest version of axios?
AXIOS VERSION used
"axios": "^1.3.2", "test": "react-scripts test --transformIgnorePatterns "node_modules/(?!axios)/"",
axiosservice.js file looks like below
import axios from 'axios'; import { qs, parse, stringify } from 'qs'; const buildInfoFilePath = '/system/buildInfo.json';
class AxiosService { instance = axios.create({ paramsSerializer: { encode: parse, serialize: stringify } });
none of the solution worked for me .
can u please guide me what exactly fixed your issue, and how your axios service.js file looks like
Advance thanks

No, I didn't. My axios service contains get, put, post and delete methods such as:

	/**
	 * GET
	 * @param url
	 * @param config
	 */
	get = async <T>(url: string, config?: AxiosRequestConfig): Promise<T> => {
		const resp = await axios.get(url, config);
		return resp.data as T;
	};

that worked for me:

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

It does even not work for me.

@paullaster
Copy link

Not working for me either

HI @imransilvake did u not faced error like "options must be an object error" with latest version of axios?

AXIOS VERSION used

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

axiosservice.js file looks like below

import axios from 'axios'; import { qs, parse, stringify } from 'qs'; const buildInfoFilePath = '/system/buildInfo.json';

class AxiosService { instance = axios.create({ paramsSerializer: { encode: parse, serialize: stringify } });

none of the solution worked for me .

can u please guide me what exactly fixed your issue, and how your axios service.js file looks like

Advance thanks

Not working me too

@rlemasquerier
Copy link

For those of you who tried transformIgnorePatterns with no success, 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...

@SalahAdDin
Copy link

For those of you who tried transformIgnorePatterns with no success, 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...

We are working with vite.

@Veryinheart
Copy link

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

joseph-ortiz pushed a commit to joseph-ortiz/bookstoreclient that referenced this issue Mar 21, 2023
@joberthrogers18
Copy link

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

Update the lib like @pzi said works to me!

@philly-vanilly
Copy link

Could you not think of releasing two different libs, one for backend, one for frontend, with different build target or something? How many human life hours have been wasted on this nonsense?

@SalahAdDin
Copy link

Could you not think of releasing two different libs, one for the backend, and one for the front end, with different build targets or something? How many human life hours have been wasted on this nonsense?

isn't this library isomorphic?

@sane4ek1994
Copy link

"test": "react-scripts test --transformIgnorePatterns "node_modules/(?!axios)/""
Thanks for the solution, saved a lot of time 🙂

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