amannn / next-intl

🌐 Internationalization (i18n) for Next.js
https://next-intl-docs.vercel.app
MIT License
2.34k stars 210 forks source link

Imports from next-intl/server break Jest due to export syntax #681

Closed sawyerh closed 9 months ago

sawyerh commented 9 months ago

Description

Jest fails to run when the tested source file has an import from next-intl/server.

Similar to #452 and #488, but a different module.

Mandatory reproduction URL (CodeSandbox or GitHub repository)

https://github.com/sawyerh/next-intl-bug-examples

Reproduction description

Adding a line like the following to a source file:

import { getTranslations } from "next-intl/server";

Then running a Jest test on that source file, results in Jest reporting:

node_modules/next-intl/dist/esm/server.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export{default as getRequestConfig}from"./server/getRequestConfig.js";export{default as getFormatter}from"./server/getFormatter.js";export{default as getNow}from"./server/getNow.js";export{default as getTimeZone}from"./server/getTimeZone.js";export{default as getTranslations}from"./server/getTranslations.js";export{default as getMessages}from"./server/getMessages.js";export{default as getLocale}from"./server/getLocale.js";export{setRequestLocale as unstable_setRequestLocale}from"./server/RequestLocale.js";
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

Expected behaviour

I would like to use Jest to test React components that import from next-intl/server without additional compiler config.

amannn commented 9 months ago

That's a fair point, thanks for the hint!

Note that next-intl/server can probably not be used in a meaningful way in unit tests with Jest currently, since it requires the RSC environment. However, in your case you're merely testing a page that happens to also have a metadata export and next-intl/server isn't used in the tested code. I think we can make this work as long as you're not invoking any functions from next-intl/server.

For other cases, next-intl/server should probably be mocked for the time being (see also https://github.com/testing-library/react-testing-library/issues/1209).