Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

299
Views
¿Cómo uso mocha y chai con un proyecto javascript heredado y no obtengo el error "no se puede encontrar el módulo"?

Estoy agregando pruebas unitarias a un proyecto php heredado que tiene muchas clases de javascript más antiguas. Especialmente, estoy tratando de escribir pruebas en un archivo que se encuentra en el directorio ./public/scripts/.

El Javascript parece que es es4 o 5.

Agregué npm package.json babel, mocah y chai al proyecto.

Sigo recibiendo el siguiente error cuando ejecuto las pruebas. Error [ERR_MODULE_NOT_FOUND]: Cannot find module '~/Development/web/OHB/dev/public/script/world' imported from ~/Development/web/OHB/dev/tests/js/world.test.js

Mi paquete.json se ve así.

 { "name": "ohb", "version": "0.0.0", "type": "module", "main": "./public/script/main.js", "description": "package management for the javascript application that configures the building configurator", "scripts": { "test": "npx mocha \"./tests/js/*.test.js\" --recursive --require @babel/register" }, "devDependencies": { "@babel/core": "^7.15.5", "@babel/preset-env": "^7.15.6", "@babel/register": "^7.15.3", "chai": "^4.3.4", "mocha": "^9.1.2" } }

El archivo javascript que intento probar está en /public/scripts/world.js y tiene este aspecto.

 import * as THREE from "../../../build/three.module.js"; import {OHBBuilding, focuspoint} from "/script/bap/building.js"; import {OrbitControls} from "/assets/js/OrbitControls.js"; export var container; export var camera, scene, renderer; export var groundMaterial, barn, controls; export var loaded3d = false; var canexpand=true; var builder; export var objects = [], plane; var raycaster = new THREE.Raycaster(); var mouse = new THREE.Vector2(), SELECTED= new THREE.Vector3(); function myTestFunction() { return {}; } ///lots of other functions below here module.exports = { myTestFunction };

mi prueba se ve así

 import { expect } from "chai"; import { myTestFunction } from "../../public/script/world"; describe('myTestFunction - does it return an object', () => { it('returns an empty object', () => { const expected = {}; const actual = myTestFunction(); expect(expected).to.deep.equal(actual); }); });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

este es un poco complicado, así que permítanme dividirlo en dos partes:

1. ERR_MODULE_NO_FOUND

Hay un mensaje que indica que no se puede encontrar el módulo porque no ha especificado la extensión. Si reemplaza la segunda línea en su prueba para:

 import { myTestFunction } from "../../public/script/world.js";

se encontrará el módulo. Sucede porque node.js no infiere la extensión del archivo. Esto se puede cambiar fácilmente agregando un argumento --es-module-specifier-resolution=node a su comando mocha:

 npx mocha \"./tests/js/*.test.js\" --recursive --require @babel/register --es-module-specifier-resolution=node

Hay documentación de node.js al respecto, aunque es una lectura bastante larga.

2. Error de referencia

Después de que tenga su archivo world.js visible desde el archivo de prueba, obtendrá otro error:

 ReferenceError: module is not defined in ES module scope This file is being treated as an ES module because it has a '.js' file extension and '/root/stack-overflow/mocha-help/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

Tienes dos formas de lidiar con eso:

  1. Debe volver a escribir export en el archivo world.js a la nueva sintaxis del módulo ES:
 export { myTestFunction };
  1. Puede cambiar el nombre del archivo a world.cjs y hacer referencia a esa extensión en el archivo de prueba.

Realmente no hay diferencia en ambos, por lo que se reduce a qué opción será más fácil de implementar.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!