Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda