Reputation: 646
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.
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:
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)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?
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/[email protected]/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/[email protected]/node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (../../node_modules/.pnpm/[email protected]/node_modules/bull/lib/scripts.js:8:18)
Upvotes: 10
Views: 5037
Reputation: 142
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.
Upvotes: 3