Having trouble running Jest tests with three objects in my Vite Vue TypeScript project

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",...
        
    

Answer №1

After discovering that OrbitControls could be obtained from a separate library, I decided to install it and update the import statement to:

import {OrbitControls} from "three-orbitcontrols-ts";

This adjustment proved successful!

However, I soon realized that this version of OrbitControls had a different interface, which meant I had to modify how its properties were referenced. This may have affected the functionality in use, but my main goal was just to ensure the tests were passing.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Truncating decimal points in JavaScript

In this scenario, if the number after the decimal point is 0, then the zero should be removed. Otherwise, the number should be displayed as it is. Here are some examples of what I am aiming for in vue: 100.023 => 100.023 1230.0 => 1230 ...

Having trouble integrating VueX store and router into Mocha tests

Latest Update To view the issue on VueX git repository that has been created, please follow this link: https://github.com/vuejs/vuex/issues/1509 If you want to replicate the problem, here is the link to the repository: https://github.com/djam90/vuex-vue- ...

Error encountered when attempting to modify an Angular expression within a table that is being edited inline

In my table, there is a child component called modal which contains two buttons - save and cancel for inline editing. I am aware that I need to utilize "ChangeDetectorRef", but I am struggling to implement the event "ngAfterViewInit" in my code. An erro ...

Integrating YouTube videos into a Three.js scene (utilizing CSS3DRenderer and WebGLRenderer)

Prior to asking a question, I want to mention that I have already attempted several methods. I have asked this question before but received no help Integrating HTML Pages Into Your WebGL stemkoski-css3d.html and more.. I am attempting to embed a YouTu ...

Toggle the visibility of a dropdown menu based on the checkbox being checked or unchecked

One challenge I am facing involves displaying and hiding DropDown/Select fields based on the state of a Checkbox. When the checkbox is checked, the Dropdown should be visible, and when unchecked, it should hide. Below is the code snippet for this component ...

Interactive feature in Three.js causes page to scroll downwards upon object selection

Exploring Three.js for the first time, I'm looking to integrate it into the landing page of my website. However, I've encountered an issue where clicking on the scene area with my object causes the page to shift downward. I've tried adding o ...

Issue: Vue Storybook encounters compilation errors when using Pug components

Currently, I am in the process of integrating Storybook into my project that is coded using Pug. However, I encountered an issue where Storybook fails to compile when I create a story with a component written in Pug. Interestingly, if I switch the templa ...

Instance property value driven class property type guard

Is it possible to create a class example that can determine the config type based on the value of animalType instance: enum Animal { BIRD = 'bird', DOG = 'dog', } type Base = { id: number } // Object example type Smth = Base & ...

Exploring advanced slot functionality in VuetifyJS through autocomplete integration with Google Places API

How can I make VuetifyJS advanced slots work seamlessly with the Google Places API? Currently, some addresses appear in the autocomplete dropdown only after clearing the input text by clicking the "x" icon in the form field. To see the problem in action, ...

Guide to Removing Nuxt Modules and Packages

Currently using Nuxt 2.13 and looking to remove some packages from my project. In the past, I simply deleted them from the package.json file and ran npm i to uninstall the package. However, now I am encountering an error: Module @nuxtjs/google-gtag not fou ...

Does Typescript extend Node.js capabilities?

I am currently developing an application using Typescript and came across some sample Node.js code online. Can I directly use the Node.js code in my Typescript application? Essentially, I am wondering if Typescript is encompassed within Node.js. A simila ...

In what ways can I align the ESLint rules of my Node.js server with those of my Vue.js frontend?

I am looking to ensure that my Node.js server-side files follow the same ESLint rules as my Vue.js frontend. The .eslintrc.js file in my Vue project is structured as follows: module.exports = { root: true, env: { node: true }, extends: ["plugin ...

Utilizing various filters and sorting options on API response within Angular 8

Upon receiving the following API response: [ { "imgPaths":[ "gallery/products/55ccb60cddb4d9bded02accb26827ce4" ], "_id":"5f3e961d65c6d591ba04f3d3", "productName":" ...

Leveraging the Spatie Laravel-activitylog package to monitor and record user activity exclusively through APIs during specific timeframes

As I work on my current project, I am implementing the Spatie Laravel-activitylog Package to monitor user logs for various activities within the project. So far, all logs are being recorded accurately. I aim to track a variety of events such as updates, ...

What is the best way to set up a Vue bus to handle global events?

I am working on a Vue project within a Node/Webpack/Vue Router environment and attempting to set up a global event handler or bus. However, I am running into an issue where it is showing as undefined. Below is how I have set it up: main.js: //Defining th ...

Testing using Vitest in the Vue 3 Suspense wrapper: A comprehensive guide

I experimented with various methods, such as utilizing await flushPromises(); or using await nextTick(); or trying component.vm.nextTich() Unfortunately, none of these approaches seem to be effective! ...

The style was not applied from because it has a MIME type of 'text/html', which is not a supported stylesheet MIME type, and strict MIME checking is turned on

I'm currently working on creating a Google web app that relies on a Google sheet in the backend. I prefer to develop locally in VSCode since the editor in Google Apps Scripts is quite limited. Additionally, I aim to incorporate Vue3 into my project. ...

I am having trouble getting the color, metalness, lights, and shaders to work properly in Three JS on my

I attempted to create a simple code using Three.js for a red colored torus with a point light and a textured surface, but unfortunately, all I achieved was a black torus that rotates. It seems like the elements in this code are not functioning as expecte ...

Discover various ways to encapsulate Vue.js components

I am currently in the process of developing a website that utilizes classic multiple pages powered by blade templates. However, I am looking to incorporate vuejs2 components for more dynamic functionalities. Although things are running smoothly, I am faci ...

Determining Velocity of an Object in Three.js

Can anyone help me figure out how to calculate an object's velocity in three.js? I've checked the Object3D documentation but can't seem to find anything related to velocity. Appreciate any assistance, ...