9

Background

I have a monorepo project built using Nx. This repo contains several reusable libraries for my backend projects. The packages is collected from several projects to create a reusable library.

I use Jest to create and run the unit test used in my monorepo.

Problem

When I run jest, on some test it will throw an error about failure to import .js files with export in them.

Strange thing is those modules have a commonjs version and I can mock those packages without problem in my other project WITHOUT monorepo structure. But when I use the same code in monorepo project (I want to make the code reusable), jest wrongly imports ESM version of the packages instead of the CJS version.

Use case:

  • I have a blob storage library which uses ali-oss internally.
  • ali-oss distributed the CJS and ESM in same package and I can mock it without problem in my other project (without monorepo)
  • When I copied the same library into my new monorepo, Jest will complain about export token inside one of ali-oss source in node_modules

Why Jest behave differently in monorepo vs normal repo? How to solve this weird jest module resolution?

Files

tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "forceConsistentCasingInFileNames": true,
    "strict": false,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true
  },
  "files": [],
  "include": ["jest.config.ts", "**/*.test.ts", "**/*.spec.ts", "**/*.d.ts"]
}

jest.config.ts:

const nxPreset = require("@nrwl/jest/preset").default;

export default {
  ...nxPreset,
  clearMocks: true,
  coverageReporters: ["lcov", "text", "text-summary", "json-summary"],
  displayName: "kafka",
  globals: {
    "ts-jest": {
      tsconfig: "<rootDir>/tsconfig.spec.json",
    },
  },
  testEnvironment: "node",
  transform: {
    "^.+\\.[tj]s$": "ts-jest"
  },
  moduleFileExtensions: ["ts", "js"],
  coverageDirectory: "../../coverage/packages/kafka",
};

Unit test:

import Bull from "bull";

import * as dlq from "../src/dlq";
import { ModuleContext} from "./context";

jest.mock("bull");

describe(ModuleContext.Root, () => {
  describe(ModuleContext.Runner, () => {
    it("success", () => {
      expect(true).toBe(true);
    })
    describe(dlq.initialize.name, () => {
      it("should return success", () => {
        const createSpy = jest
          .spyOn(Bull.prototype, "process")
          .mockResolvedValue(null);

        dlq.initialize();
        expect(createSpy).toBeCalled();
      });
    });
  });
});

Jest output:

 FAIL   kafka  packages/kafka/test/dlq.spec.ts
  ● 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/fahmi/logee/logee-ct/logeect-libraries-monorepo/node_modules/.pnpm/msgpackr@1.6.2/node_modules/msgpackr/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { Packr, Encoder, addExtension, pack, encode, NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT, REUSE_BUFFER_MODE } from './pack.js'
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

      at Runtime.createScriptFromCode (../../node_modules/.pnpm/jest-runtime@28.1.3/node_modules/jest-runtime/build/index.js:1796:14)
      at Object.<anonymous> (../../node_modules/.pnpm/bull@4.8.5/node_modules/bull/lib/scripts.js:8:18)
Fahmi Noor Fiqri
  • 441
  • 7
  • 15

1 Answers1

3

Following Nx migration steps described here I could successfully bypass that error.

npx nx migrate latest
npx nx migrate --run-migrations

You can see in the updated files that Nx automatically updates your jest config with the following transform field:

  transform: {
    '^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '@nrwl/react/plugins/jest', // My config from before
    '^.+\\.[tj]sx?$': ['babel-jest', { presets: ['@nrwl/react/babel'] }], // Added by Nx under the migration
  },

Hope this helps.

Marion LP
  • 142
  • 5
  • Thanks for the insight, but I'm currently not using react – Fahmi Noor Fiqri Oct 20 '22 at 14:38
  • I had the latest version of `nx`, i.e. `npx nx migrate latest` didn't create any migration file (so it said). However, your answer fixed this for me. I updated my `jest.config.ts` file in all my apps to match your snippet, and it worked. Thank you . – Sadra Abedinzadeh Oct 26 '22 at 23:26
  • I updated this in the `jest.config.ts` and it fixed the tests not running in my IntelliJ IDE, but working when run with `nx run`. Didn't need to fully migrate and upgrade nx. – dijonkitchen Dec 21 '22 at 22:01