Here is a snippet of code that I am testing:
import {Line} from "../src/modules/objs/line";
import {SceneWrapper} from "../src/modules/scene/sceneWrapper";
import * as THREE from "three";
import {DrawProfile} from "../src/modules/operations/draw/drawProfile";
import {snapIndicator} from "../src/modules/config/objs";
describe('snaps', () => {
let sceneWrapper = new SceneWrapper(new HTMLCanvasElement());
let lineStart = new THREE.Vector3(0, 0, 0);
let cursorStart = sceneWrapper.getScreenCoordsFromSceneCoords(lineStart);
let line = new Line(lineStart, new THREE.Vector3(10, 10, 10));
sceneWrapper.scene.add(line);
test('Box appear', () => {
let operation = new DrawProfile(sceneWrapper);
let startEvent = new PointerEvent('', {clientX: cursorStart.x, clientY: cursorStart.y});
operation.searchSnapsHandler(startEvent);
expect(operation.snap).toBeDefined();
expect(sceneWrapper.scene).toContain(snapIndicator);
expect(snapIndicator.position).toBe(lineStart);
});
});
Jest configuration file (jest.config.cjs
):
module.exports = {
preset: 'ts-jest/presets/js-with-ts-esm',
testEnvironment: 'jsdom',
};
When running the tests with jest
, an error is encountered:
/Users/a/Programming/JavaScript/CAD/test/main.test.ts:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { Line } from "../src/modules/objs/line";
^^^^^^
SyntaxError: Cannot use import statement outside a module
By updating the Jest configuration in jest.config.cjs
:
module.exports = {
preset: 'ts-jest/presets/js-with-ts-esm',
testEnvironment: 'jsdom',
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1',
},
};
Running the tests again results in another error:
/Users/a/Programming/JavaScript/CAD/node_modules/three/examples/jsm/controls/OrbitControls.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import {
^^^^^^
SyntaxError: Cannot use import statement outside a module
The documentation suggests using
NODE_OPTIONS=--experimental-vm-modules jest
to resolve this issue:
/Users/a/Programming/JavaScript/CAD/node_modules/vue/dist/vue.runtime.esm-bundler.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { initCustomFormatter, warn } from '@vue/runtime-dom';
^^^^^^
SyntaxError: Cannot use import statement outside a module
Additional configurations are specified in tsconfig.json
:
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"jsx": "preserve",
"resolveJsonModule": true,...
Lastly, the project's package.json
contains dependencies and scripts for building and testing:
{
"name": "cad",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",...