Search code examples
javascriptunit-testingmocha.jschaitest-runner

Possible to run mocha test with chai in console and browser within a single test file?


I have set-up a little test environment for a project. It should use mocha and chai for unit testing. I've set up a html file as test runner:

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

The chaiTest.js file continas this simple test:

let assert = chai.assert;

describe('simple test', () => {
    it('should be equal', () => {
        assert.equal(1, 1);
    });
});

When I now call the test runner in my browser, the results are shown correctly. It works fine. But when I run mocha on console, it tells me that chai is not defined.

So to get this working in console, I just add a require of chai in the fist line of the test file.

let chai = require('chai');

Now the test runs fine in console, but when I execute tests in the browser, it tells me that require is undefined.

I know, these errors totally makes sense here! They are undefined. But is there a way to write tests with mocha and chai and let them execute in browser and console?

I know I could create two test files, for browser and console. But that would be hard to maintain. So I would like to write a single test file, executing correctly in both environments ...


Solution

  • I found a solution by myself now. It's needed to use a configuration file for chai. Like in my case, I called it chaiconf.js. In this file can be written a default setup of chai. This file will be required before each tests.

    My chaiconf.js:

    let chai = require("chai");
    
    // print stack trace on assertion errors
    chai.config.includeStack = true;
    
    // register globals
    global.AssertionError = chai.AssertionError;
    global.Assertion = chai.Assertion;
    global.expect = chai.expect;
    global.assert = chai.assert;
    
    // enable should style
    chai.should();
    

    Now append this configuration to every test. For this create a script entry in the package.json:

    "scripts": {
      "test": "mocha --require chaiconf.js"
    },
    

    Now, whenever you use npm test in console, the chaiconf.js will be required before tests and make chai globally available, like in the browser.


    Another way without a configuration file would be to use an inline decision to receive chai:

    let globChai = typeof require === 'undefined' ? chai : require('chai');