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

next-intl/link and useRouter is causing an error in Jest tests #488

Closed
cjambrosi opened this issue Aug 30, 2023 · 5 comments · Fixed by #149
Closed

next-intl/link and useRouter is causing an error in Jest tests #488

cjambrosi opened this issue Aug 30, 2023 · 5 comments · Fixed by #149
Labels
bug Something isn't working unconfirmed Needs triage.

Comments

@cjambrosi
Copy link

Description

Environment

  • Node: v18.16.0
  • OS: MacOS Ventura 13.4
  • Yarn: v1.22.19

Libs

  • nextjs: v13.4.6
  • next-intl: v2.20.0
  • Jest: v29.6.2

The errors occur in all component tests that use next-intl/link or useRouter (maybe it happens to others too).
This error has already been reported in another issue, but in next-intl 3.0.0-beta.9 version.

next-intl/link error:

$ jest --config=jest.config.js --no-cache
 FAIL  src/components/Card/index.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/cjambrosi/GitHub/next-intl-jest-error-reproduce/node_modules/next-intl/dist/src/link/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default } from './Link';
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

      10 | }
      11 |

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)
      at Object.<anonymous> (src/components/I18nLink.tsx:12:54)
      at Object.<anonymous> (src/components/Card/Card.tsx:12:58)
      at Object.<anonymous> (src/components/Card/index.test.tsx:6:54)

useRouter error:

$ jest --config=jest.config.js --no-cache
 FAIL  src/components/Card/index.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/cjambrosi/GitHub/next-intl-jest-error-reproduce/node_modules/next-intl/dist/src/client/index.js:4
    export { default as useRouter } from './useRouter';
    ^^^^^^

    SyntaxError: Unexpected token 'export'

      10 |   }

Mandatory reproduction URL (CodeSandbox or GitHub repository)

https://github.com/cjambrosi/next-intl-jest-error-reproduce

Reproduction description

Steps to reproduce:

  1. Open reproduction
  2. Install dependencies
  3. Run tests with yarn test command
  4. See the error SyntaxError: Unexpected token 'export'

Expected behaviour

No error.

@amannn
Copy link
Owner

amannn commented Aug 30, 2023

Thank you for the great report!

Hmm, I'm really curious why jest works internally in the monorepo of next-intl but not when next-intl is installed externally. When I copy example-next-13 outside of the repo and install the dependencies, then I can reproduce your error there too.

Anyway, jest doesn't support ES modules out of the box and currently in the stable release, the entry point for /client points to one. #149 improves the bundling and will fix this issue since it uses CommonJS for all entrypoints.

In the meantime, you can use this workaround:

index b1df010..5145857 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -22,4 +22,21 @@ const customJestConfig = {
   setupFilesAfterEnv: ['@testing-library/jest-dom', '<rootDir>/jest.setup.tsx'],
 };
 
-module.exports = createJestConfig(customJestConfig);
+module.exports = async () => ({
+  ...(await createJestConfig(customJestConfig)()),
+
+  // https://github.com/vercel/next.js/issues/36077#issuecomment-1096635363
+  transformIgnorePatterns: [
+    'node_modules/(?!(' +
+      [
+        '@formatjs/icu-messageformat-parser',
+        '@formatjs/icu-skeleton-parser',
+        '@formatjs/fast-memoize',
+        'next-intl',
+        'use-intl',
+        'intl-messageformat',
+        'tslib'
+      ].join('|') +
+      ')/)'
+  ]
+});

Thanks to @barbarah, this is based on https://github.com/colonial-heritage/colonial-collections/blob/main/apps/researcher/jest.config.js.

Sorry for the inconvenience!

@cjambrosi
Copy link
Author

Thanks for the sugestion. I chose to use the [email protected] version, but now the following error occurs when trying to use useRouter().
Is it missing some configuration or could it really be an incompatibility error?

useRouter error with [email protected]:

  console.error
    The above error occurred in the <Card> component:
    
        at useRouter (/Users/cjambrosi/GitHub/next-intl-jest-error-reproduce/src/components/Card/Card.tsx:7:18)
        at children (/Users/cjambrosi/GitHub/next-intl-jest-error-reproduce/node_modules/use-intl/dist/use-intl.cjs.development.js:663:23)
        at children (/Users/cjambrosi/GitHub/next-intl-jest-error-reproduce/node_modules/next-intl/dist/shared/next-intl.cjs.development.js:17:23)
    
    Consider adding an error boundary to your tree to customize error handling behavior.
    Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

      19 | ) => {
      20 |   const locale = providerProps?.locale || defaultProviderProps.locale;
    > 21 |   return render(
         |          ^
      22 |     <NextIntlClientProvider
      23 |       locale={locale}
      24 |       messages={{

      at logCapturedError (node_modules/react-dom/cjs/react-dom.development.js:18687:23)
      at Function.render [as customRender] (jest.setup.tsx:21:10)
      at Object.customRender (src/components/Card/index.test.tsx:6:10)

src/components/Card/index.test.tsx
  Home
    ✕ Should render Card component (86 ms)

  ● Home › Should render Card component

    invariant expected app router to be mounted

       5 |
       6 | export default function Card() {
    >  7 |   const router = useRouter()
         |                  ^
       8 |
       9 |   const handleClick = (e) => {
      10 |     e.preventDefault()

      at Object.useRouter (node_modules/next/src/client/components/navigation.ts:123:11)
      at useRouter (src/components/Card/Card.tsx:7:18)
      at Function.render [as customRender] (jest.setup.tsx:21:10)
      at Object.customRender (src/components/Card/index.test.tsx:6:10)

@amannn
Copy link
Owner

amannn commented Aug 31, 2023

You probably have to mock next/navigation, since as it mentions:

expected app router to be mounted

@amannn
Copy link
Owner

amannn commented Aug 31, 2023

FWIW I've also just resolved a bug with jest where I got the same error message, but I think it's more related to me using pnpm and symlinks here.

This was the fix: 88df0fe

@cjambrosi
Copy link
Author

Thank you for helping me @amannn. I managed to solve the useRouter problem in my project using the yoshiomiyamae solution in discussion #48937.

amannn added a commit that referenced this issue Nov 14, 2023
→ Please refer to [the
announcement](https://next-intl-docs.vercel.app/blog/next-intl-3-0)


Fixes #488
Fixes #402
Fixes #578

---------

Co-authored-by: 汪心禾 <[email protected]>
Co-authored-by: Tobias <[email protected]>
Co-authored-by: Andres <[email protected]>
Co-authored-by: Andres <[email protected]>
Co-authored-by: narakhan <[email protected]>
Co-authored-by: Nicholas Mobbs <[email protected]>
Co-authored-by: James Berry <[email protected]>
Co-authored-by: Brendon Sled <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working unconfirmed Needs triage.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants