Reputation: 52
I'm trying to run Typescript tests that run Typescript code with Jest. I've tried to configure Jest with ts-jest in multiple shapes, but without success.
I obtain:
node_modules/@polkadot/api/promise/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import log4js from "log4js";
> 2 | import { ApiPromise } from "@polkadot/api/promise";
| ^
My jest.config.ts:
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
import type { Config } from "@jest/types";
// Sync object
const config: Config.InitialOptions = {
roots: ["./"],
preset: "ts-jest",
coverageDirectory: "../coverage",
verbose: true,
testEnvironment: "node",
//setupFilesAfterEnv: ["./jest.setup.ts"],
testMatch: ["**/?(*.)+(test).ts"],
resetMocks: true,
clearMocks: true,
extensionsToTreatAsEsm: [".ts"],
transformIgnorePatterns: ["node_modules/(?!(@polkadot)/)"],
//collectCoverage: true
};
export default config;
I run the tests with: "jest --config src/test/jest.config.ts --detectOpenHandles"
Any ideas on how to solve this?
I've also tried to execute my code with TAP, but also unsuccessfully. I would appreciate guidance to solve either of the problems, provided that the async tests can run.
Upvotes: 1
Views: 1991
Reputation: 293
Did you setup jest with Babel? Jest
doesn't understand Typescript so it relies on babel for transpiling.
Upvotes: 1
Reputation: 31
This problem first and foremost has to do with the fact that all code in node_modules
will not be transformed before Jest executes, and Jest can only process CommonJS code. You have to add transformIgnorePatterns
in order to transform ESM code inside your node_modules
to CJS. Have a look at this example for how you actually set it up correctly.
Upvotes: 0