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

157
Views
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
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!