sindresorhus / query-string

Parse and stringify URL query strings
MIT License
6.73k stars 449 forks source link

when update to version 8 broke my application #366

Closed jadir-junior closed 1 year ago

jadir-junior commented 1 year ago

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 commented 1 year ago

https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c

lukasvice commented 1 year ago

With version 8, I had to use

import queryString from 'query-string'

queryString.stringify(queryParams)
varshagada commented 1 year ago

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 commented 1 year ago

@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 commented 1 year ago

@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 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago
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 commented 1 year ago

For those using NextJS 13 and mocking isn't an option, this did the trick for me: https://github.com/vercel/next.js/issues/36077#issuecomment-1096635363

raybrownco commented 11 months ago

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 commented 9 months ago

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 commented 6 months ago

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 commented 6 months ago

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