Currently, I am attempting to develop an extension based on jest-node-environment
as a CustomTestEnvironment
. However, I encountered an error when trying to execute jest:
● Test suite failed to run
~/git/my-application/tests/environment/custom-test-environment.ts:1
import NodeEnvironment from 'jest-environment-node';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at runTestInternal (../node_modules/jest-runner/build/runTest.js:226:5)
It seems that the issue stems from the file not being recognized as TypeScript or properly transpiled. Even with the latest version of jest 26.0.1, the error persists.
Discussions on the jest GitHub revealed that the fix was intended for Jest 26 but deferred to Jest 27. https://github.com/facebook/jest/pull/8751
Although there are online examples suggesting a workaround, my attempts have been unsuccessful.
import NodeEnvironment from "jest-environment-node";
import {LocalObject} from "./object/local-object.helper";
export class CustomTestEnvironment extends NodeEnvironment {
public async setup(): Promise<void> {
await super.setup();
this.global.localObject = LocalObject.init()
}
public async teardown(): Promise<void> {
LocalObject.teardown(this.global.localObject)
await super.teardown();
}
}
The purpose of the LocalObject is to encapsulate a test utility with complex initialization and cleanup processes meant to provide test data and trigger component testing.
When attempting to switch the imports to require statements -
const NodeEnvironment = require("jest-environment-node");
const {LocalObject} = require("./object/local-object.helper");
A new error emerges -
SyntaxError: Unexpected token 'export'
Further adjustments like using module.exports
or altering syntax lead to different errors, indicating a persistent TypeScript recognition issue.
Is there any viable solution to utilize this as a TypeScript file? Since the LocalObject is defined in TypeScript, maintaining its integrity is crucial for proper usage within test files.
Alternatively, is it feasible to implement similar setup/teardown logic in the setupFilesAfterEnv
section after tests execution? I only observed they are executed before tests. Thank you.