sinonjs / sinon

Test spies, stubs and mocks for JavaScript.
https://sinonjs.org/
Other
9.61k stars 769 forks source link

SyntaxError: Unexpected token 'export' on the latest version of sinon 15.2.0 with jest #2522

Closed hrai closed 1 year ago

hrai commented 1 year ago

Describe the bug I'm getting error while importing sinon that's setup with jest.

This error does not exist in v14.0.2

Expected behavior When running yarn jest it should not produce the error below.

Screenshots image

Context (please complete the following information):

Additional context Add any other context about the problem here.

Even adding below doesn't solve the problem.

  "transformIgnorePatterns": [
    "/node_modules/(?!(sinon)/)"
  ],
McFoggy commented 1 year ago

we faced exactly the same using jest and had to revert to version sinon@15.1.2

transformIgnorePatterns did not solved our issue neither.

tjunghans commented 1 year ago

If you're still riding the commonJS wave then adding the following to your jest config fixes the issue:

moduleNameMapper: {
  sinon: "<rootDir>/node_modules/sinon/pkg/sinon.js",
},
fatso83 commented 1 year ago

The relevant change is mentioned in the changelog, specifically this commit for Webpack 5 compatibility. Our semvers are for API changes in the library, not with regards to bundler compatibility, so things like this could break in a minor verrsion.

I am not sure why Jest picks up the module from browser field (the only change), though, which is a bit strange, but still does not make it a bug in Sinon's config. You can use @tjunghans workaround, if needed.


I read up a bit on this through https://github.com/jestjs/jest/issues/9771 and Jest's Configuration pages. The bit mentioning customExportConditions seems to apply:

Both jest-environment-jsdom and jest-environment-node allow specifying customExportConditions, which allow you to control which versions of a library are loaded from exports in package.json. jest-environment-jsdom defaults to ['browser']. jest-environment-node defaults to ['node', 'node-addons'].

That probably explains it, if you are using jsdom or something else setting customExportConditions in the test environment to "browser".

hrai commented 1 year ago

According to the comments, I added the config but the issue persists.

image

tjunghans commented 1 year ago

@hrai Try "node" instead of "browser".

fatso83 commented 1 year ago

@hrai Sorry for being unclear. I can see that this sentence can be seen as ambiguous:

That probably explains it, if you are using jsdom or something else setting customExportConditions in the test environment to "browser".

What I meant to say was that if jsdom (or something else) is setting customExportConditions to "browser", that would explain your problem. The fix is then to set it to something else than that, like @tjunghans proposed .

fatso83 commented 1 year ago

If someone would like this to appear in our official sinonjs.org docs, we ❤️ PR's! Here is how.