testingjestjsreact-testing-libraryes6-modulescommonjs

Jest tests are failing because of an unknown unexpected token "export"


I'm using tRPC with Typescript and Next.js. My tests used to not fail until recently (I don't think I touched them). I get the error Unexpected token 'export'. I've tried changing my jest.config.mjs to add transformIgnorePatterns: ["!node_modules/"] as well as babel-jest with

   transform: {
      "^.+\\.tsx?$": "ts-jest",
      "^.+\\.(js|jsx)$": "babel-jest",
      "node_modules/variables/.+\\.(j|t)sx?$": "babel-jest"
    },

but to no avail :( Can someone help me please? Here's my error logs.

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/runner/work/workout-app/workout-app/node_modules/jose/dist/browser/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { compactDecrypt } from './jwe/compact/decrypt.js';
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

      19 |   return `http://localhost:${process.env.PORT ?? 3000}`
      20 | }
    > 21 |
         | ^
      22 | export const trpc = createTRPCNext<AppRouter>({
      23 |   // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
      24 |   config(opts) {

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1495:14)
      at Object.<anonymous> (node_modules/@supabase/auth-helpers-shared/src/utils/cookies.ts:3:27)
      at Object.<anonymous> (node_modules/@supabase/auth-helpers-nextjs/src/clientComponentClient.ts:6:8)
      at Object.<anonymous> (src/utils/trpc.ts:21:28)
      at Object.<anonymous> (src/hooks/useMutationDeleteWorkoutPlan.tsx:11:15)
      at Object.<anonymous> (src/components/Workouts/index.tsx:16:78)
      at Object.<anonymous> (src/__tests__/jest/Workouts.test.tsx:9:58)

Here's my jest.config.mjs

import nextJest from "next/jest.js"

const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: "./",
})

// Add any custom config to be passed to Jest
/** @type {import('jest').Config} */
const config = {
  // Add more setup options before each test is run
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  testEnvironment: "jest-environment-jsdom",
}

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config)


Solution

  • For those who came to the thread hoping for a solution, this is mine :

    Add "^jose": require.resolve("jose"), to moduleNameMapper of jest config (And other module with same issue...). I also had to fix the TextEncoder issue with a jest setup file.

    
    // jest.config
    const customJestConfig = {
      setupFiles: ["./setup.jest.ts"],
      moduleNameMapper: {
        "^jose": require.resolve("jose"),
        "^@panva/hkdf": require.resolve("@panva/hkdf"),
        "^preact-render-to-string": require.resolve("preact-render-to-string"),
        "^preact": require.resolve("preact"),
        "^uuid": require.resolve("uuid")
      },
      //...
    };
    
    
    // setup.jest.ts
    const { TextEncoder, TextDecoder } = require("util");
    
    Object.assign(global, { TextDecoder, TextEncoder });