Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
Testing with mocha/chai for browser and nodejs

Im trying to set up a testing environment and I am having issues with the imports. Assume following files:

test/tests.js:

describe("test1", () =>
  it('should pass', () => {
   chai.assert.equal(1, 1)
 })
)

test.html:

<!DOCTYPE html>
<html>
<head>
  <title>Mocha Tests</title>
  <link rel="stylesheet" href="node_modules/mocha/mocha.css">
</head>
<body>
  <div id="mocha"></div>-
  <script type="module" src="./node_modules/chai/chai.js"></script>
  <script src="node_modules/mocha/mocha.js"></script>
  <script>mocha.setup('bdd')</script>
  <script type="module" src="test/tests.js"></script>
  <script>
    mocha.run();
  </script>
</body>
</html>

package.json:

{
  "name": "test",
  "version": "1.0.0",
  "scripts": {
    "test": "mocha",
    "server": "static"
  },
  "type": "module",
  "license": "AGPL-3.0-or-later",
  "devDependencies": {
    "chai": "^4.3.6",
    "mocha": "^9.2.2",
    "node-static": "^0.7.11"
  },
  "directories": {
    "test": "test"
  }
}

This code allows me to run the tests in the browser, as the import with <script> sets a global chai object. But when I run the tests in node with npm run test, they obviously don't work since chai is not imported here. When I try to fix that by changing the tests.js file to this:

import chai from '../node_modules/chai/chai.js'; //import with full relative Path, required by ES6
const {assert} = chai;

describe("test1", () =>
  it('should pass', () => {
    assert.equal(1, 1)
  })
)

This will work in node, but NOW the browser will have an error: Error: Uncaught SyntaxError: The requested module '../node_modules/chai/chai.js' does not provide an export named 'default' (http://127.0.0.1:8080/test/tests.js:1)

Also, only importing assert from chai will have the same error. Maybe this library is not made for the ES6 import way? Importing with require() works in node, but this (commonjs) way is not supported in browser.

Is there a way to get the tests in both environments running, without using some bundler?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda