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

when update to version 8 broke my application #366

Closed
jadir-junior opened this issue Dec 24, 2022 · 19 comments
Closed

when update to version 8 broke my application #366

jadir-junior opened this issue Dec 24, 2022 · 19 comments

Comments

@jadir-junior
Copy link

In version 7.1.3 I can import stringify

import {stringify} from 'query-string'

now in version ^8 a I can't, and when I try to refactor the code to import queryString and use queryString.stringify my tests with jest broken like that:

 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:

    /home/jadirjsjunior/Projects/healthcare/healthcare-front/node_modules/query-string/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import * as queryString from './base.js';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      4 | import { Observable } from 'rxjs'
      5 | import { environment } from 'src/environments/environment'
    > 6 | import queryString from 'query-string'
        | ^
@sindresorhus
Copy link
Owner

@lukasvice
Copy link

lukasvice commented Jan 26, 2023

With version 8, I had to use

import queryString from 'query-string'

queryString.stringify(queryParams)

@varshagada
Copy link

Even I am facing the same issue. After upgrading to version 8 , my tests start to fail. I tried all the steps https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c but none of them worked. Can anyone suggest solution to it?

@cbrenner04
Copy link

@sindresorhus I am not sure how your response answers the question. I am probably being a little dense. Unlike @lukasvice, I was already importing query-string that way. I tried a few different things listed in your link to no avail. If its not too much trouble, would you mind being a little more precise with your response? Thank you!

@jadir-junior if you resolved this, please respond with your fix. Thank you!

@smajl
Copy link

smajl commented Feb 10, 2023

@jadir-junior @varshagada @cbrenner04 In your main Jest preset file you should have smth like this:

const esModules = [
  'other_modules_based_on_your_needs',
  // but mainly those 4 bellow
  'query-string',
  'decode-uri-component',
  'split-on-first',
  'filter-obj',
];

module.exports = {
  ...
  transformIgnorePatterns: esModules.length ? [`/node_modules/(?!${esModules.join('|')})`] : [],
  ...
}

Basically I had to add not only query-string but also its 3 dependencies.

@varshagada
Copy link

Even I am facing the same issue. After upgrading to version 8 , my tests start to fail. I tried all the steps https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c but none of them worked. Can anyone suggest solution to it?

I got it solved by mocking the Query-string in my test files.

sample.test.js

import queryString from 'query-string'

jest.mock('query-string' , () => ({
//mock whatever you use from query-string
parse :jest.fn(),
stringify: jest.fn()
}));

Thankyou

@yvbeek
Copy link

yvbeek commented Feb 22, 2023

Similar to @smajl 's solution. You can also add the following section to your package.json:

  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!(@react-native|react-native|decode-uri-component|filter-obj|split-on-first|query-string)/)"
    ]
  }

Note: I'm using React-Native, if you aren't, you'll have to tweak it a bit.

@rodrigo-gross
Copy link

Similar to @smajl 's solution. You can also add the following section to your package.json:

  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!(@react-native|react-native|decode-uri-component|filter-obj|split-on-first|query-string)/)"
    ]
  }

Note: I'm using React-Native, if you aren't, you'll have to tweak it a bit.

This worked for me, thanks

@danvoyce
Copy link

I'm also having this issue. I can't mock this out as it's critical to my app and needs testing.

Adding transformIgnorePatterns doesn't seem to work for me either.

@sindresorhus any help on this would be really appreciated 🙏 The link you provided above doesn't work, and this issue shouldn't really be closed.

@juancho11gm
Copy link

I had to install @babel/plugin-proposal-private-methods and add it to the jest.config.ts file. Also, some node modules packages were included in the transformIgnorePatterns option.

	transformIgnorePatterns: [
		'node_modules/(?!(query-string|decode-uri-component|split-on-first|filter-obj)/)',
	],
	babelConfig: {
		plugins: ['@babel/plugin-proposal-private-methods'],
	},

@athielba
Copy link

athielba commented Jun 7, 2023

In my case, I just added the following code in the jest.config.js

module.exports = {
 ...
  transformIgnorePatterns: [
      'node_modules/(?!(query-string|decode-uri-component|split-on-first|filter-obj)/)',
  ],
}

@EperezOk
Copy link

EperezOk commented Jul 6, 2023

The transformIgnorePatterns didn't work for me (I have a NextJS 12 app), I had to mock the library.
Inside jest.setup.js:

jest.mock("query-string" , () => ({
    __esModule: true,
    default: {
        parse :jest.fn(),
        stringify: jest.fn()
    }
}))

@Chanki-Min
Copy link

For some PNPM hitchhikers who getting this problem again when migrated PNPM form npm. You need to add .pnpm/ subdir right after node_modules

const esModules = [
  'other_modules_based_on_your_needs',
  // but mainly those 4 bellow
  'query-string',
  'decode-uri-component',
  'split-on-first',
  'filter-obj',
];

module.exports = {
  ...
  transformIgnorePatterns: esModules.length ? [`/node_modules/.pnpm/(?!${esModules.join('|')})`] : [],
  ...
}

@arnoldc
Copy link

arnoldc commented Aug 22, 2023

jest.mock("query-string" , () => {
    const actualQueryString = jest.requireActual("query-string");
    return {
      __esModule: true,
      default: {
          parse :actualQueryString.default.parse,
          stringify: actualQueryString.default.stringify,
      },
    };
});

I had done this in my side ^ + the transformIgnorePatterns changes
, so i can still make use of the actual library method and it works ,
thanks for the suggestion guys

@rfviolato
Copy link

For those using NextJS 13 and mocking isn't an option, this did the trick for me: vercel/next.js#36077 (comment)

@raybrownco
Copy link

I solved this a different way: by relying on the URLSearchParams web API instead. This allowed me to remove the query-string package completely with a trivial amount of effort.

The biggest hangup I had was that URLSearchParams doesn't support the bracket array syntax, but it's pretty easy to find ways around that via Google or ChatGPT or whatever.

@njzjz
Copy link

njzjz commented Jan 6, 2024

I solved this a different way: by relying on the URLSearchParams web API instead. This allowed me to remove the query-string package completely with a trivial amount of effort.

This workaround works for me. My usage is very simple, so I just replace

  const queryString = require('query-string');
  const parsed = queryString.parse(location.search);
  const jdata = parsed['jdata'];

with

  const parsed = new URLSearchParams(location.search);
  const jdata = parsed.get("jdata");

@clintonb
Copy link

clintonb commented Mar 8, 2024

None of this worked for me. I, too, only want to get array brackets. Here is how to do so natively in Node.js.

const params = new URLSearchParams();
params.append('barcode', barcode);
storeIDs.forEach((storeID) => params.append('store_ids[]', storeID));

// barcode=04003100&store_ids[]=775
const qs = params.toString();

@rathpc
Copy link

rathpc commented Mar 22, 2024

For some PNPM hitchhikers who getting this problem again when migrated PNPM form npm. You need to add .pnpm/ subdir right after node_modules

const esModules = [
  'other_modules_based_on_your_needs',
  // but mainly those 4 bellow
  'query-string',
  'decode-uri-component',
  'split-on-first',
  'filter-obj',
];

module.exports = {
  ...
  transformIgnorePatterns: esModules.length ? [`/node_modules/.pnpm/(?!${esModules.join('|')})`] : [],
  ...
}

@Chanki-Min Thank you so much for this, I was losing my mind!!!

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