Using HTML reporting with Mocha test framework

19,771

Solution 1

To get Mocha to run your test in both browser and in the terminal follow this small tutorial:

I'm assuming the following plugins for a normal node.js mocha test suite.

  1. Node.js
  2. Mocha

And the following tree structure:

/root
  /test
    my_something_spec.js
  /javascript
  index.html

index.html

Disclaimer: I've blatantly forgone all kinds of best practices but just to point you in the right direction.

<html>
<head>
    <meta charset="utf-8">
    <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>mocha.setup('bdd')</script>
    <script src="test/my_something_spec.js"></script>
    <script>
        mocha.checkLeaks();
        mocha.run();
    </script>
</body>
</html> 

test/my_something_spec.js

describe("my function", function() {
  it("is a function", function() {
    expect(true).to.be(true);
  });
});

Serving this up with a simple python server python -m SimpleHTTPServer 8080 from the root and visit localhost:8080 will give you a nice and failing test. And running mocha from the terminal will give you the same output, that expect isn't defined.

Solution 2

You try to use the html reporter, which throws when you try to use it in Node:

$ mocha --reporter html > report.html

/usr/local/lib/node_modules/mocha/lib/reporters/html.js:194
    , div = document.createElement('div')
            ^
ReferenceError: document is not defined

Per the Mocha documentation (and relevant issue in Github), the htmlreporter only works in the browser, ie. to test client-side code in the browser.

If you want to output HTML for a Node.js test script, use the doc reporter, which will generate HTML.

Solution 3

I like to test the same code through Node.js and in a browser, depending on the situation. I know you were asking to "place the results into a browser" (from Node.js?), but I hope this will suffice.

This example was created on a windows machine, but it will work on a Mac and Linux also.

You do not require a web-server (Node.js or other) for this to work.

To run the tests in a browser, open up the ./test/index.html file.

To run the tests in command-line, just execute "mocha".

Starting from nothing:

C:\TEMP>mkdir mocha_node_browser

C:\TEMP>cd mocha_node_browser

C:\TEMP\mocha_node_browser>dir
Volume in drive C is MessedUp
Volume Serial Number is CAB2-E609

Directory of C:\TEMP\mocha_node_browser

2014-08-09  12:17    <DIR>          .
2014-08-09  12:17    <DIR>          ..
               0 File(s)              0 bytes
               2 Dir(s)  287,218,769,920 bytes free

Initialize the directory that will hold all of your tests. Always call it "test":

C:\TEMP\mocha_node_browser>mocha init test

Edit and/or create some files:

C:\TEMP\mocha_node_browser>gvim -p test_me.js test\index.html test\tests.js

I use Chai. The same chai.js file will be used in both tests.

C:\TEMP\mocha_node_browser>cd test

C:\TEMP\mocha_node_browser\test>curl -O http://chaijs.com/chai.js
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  117k  100  117k    0     0  99902      0  0:00:01  0:00:01 --:--:-- 99902

C:\TEMP\mocha_node_browser\test>cd ..

After creating/editing the files, run the tests via command-line:

C:\TEMP\mocha_node_browser>mocha

  .

  1 passing (15ms)

...or point your browser at ./test/index.html.

passes: 1
failures: 0
duration: 0.03s

whatever
    should return "it worked!"

File contents:

C:\TEMP\mocha_node_browser>type test_me.js

// the function to be tested
function whatever() {
  return 'it worked!';
}

// only kicks in when running in Node.js via "mocha"
if (typeof module !== 'undefined') {
  module.exports = whatever;
}

Add Chai and your source that you want to test into test/index.html:

C:\TEMP\mocha_node_browser>type test\index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Mocha</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="mocha.css" />
  </head>
  <body>
    <div id="mocha"></div>
    <script src="mocha.js"></script>
    <script>mocha.setup('bdd')</script>

    <!-- added to index.html: -->
    <script src="./chai.js"></script>
    <script src="../test_me.js"></script>

    <script src="tests.js"></script>
    <script>
      mocha.run();
    </script>
  </body>
</html>

Make your tests compatible with command-line and browser

C:\TEMP\mocha_node_browser>type test\tests.js

if (typeof require !== 'undefined') {
  // testing in command-line
  var chai = require('./chai');
  var whatever = require('../test_me');
}

var expect = chai.expect;

describe('whatever', function() {
  it('should return "it worked!"', function() {
    expect(whatever()).to.equal("it worked!");
  });
});
Share:
19,771

Related videos on Youtube

whitfin
Author by

whitfin

Know various things, the things I don't know I research, for the things I can't research I find myself here...

Updated on September 16, 2022

Comments

  • whitfin
    whitfin over 1 year

    I've been generating some tests using NodeJS and Mocha, and I'd like to find a way to place the results into a browser. I know that Mocha has support for this using 'html' reporter and mocha init <dir> however neither seem to be working for me (the reporter actually throws errors without even running a test).

    Could someone give me a good example of running a test via Mocha and generating a HTML report?An example I want to mimic is on the visionmedia site. Also, for examples sake we'll say I'm using a test file called example.js.

    Thanks in advance for any assistance, it's surprising there are so few example pieces around.

    • thecoop
      thecoop over 10 years
      Unfortunately, doc doesn't actually say whether each test is passing or failing...
  • whitfin
    whitfin over 10 years
    Ah, so there's no way I can use the browser support section alongside Node?
  • Henrik Andersson
    Henrik Andersson over 10 years
    Yes, there is. It requires more setup if you want your stuff to work in both node and the browser.
  • whitfin
    whitfin over 10 years
    @limelights Am I to assume you're planning on answering too? :p
  • Paul Mougel
    Paul Mougel over 10 years
    I guess you can't. If you look it the source code of the html reporter, it makes a heavy use of the DOM API, which isn't available in Node.js...
  • Henrik Andersson
    Henrik Andersson over 10 years
    @Zackehh9lives I will but not now, as I'm quite strapped for time! :)
  • whitfin
    whitfin over 10 years
    @limelights Awesome, look forward to the alternative!
  • whitfin
    whitfin over 10 years
    @PaulMougel Thanks for the responses + links, it never even occurred to me it might be because it was Node and not plain JS
  • Paul Mougel
    Paul Mougel over 10 years
    I guess this won't work if the OP wants to test Node.js-only code (eg. streams, fs or http modules)?
  • Henrik Andersson
    Henrik Andersson over 10 years
    Well, both yes and no. If OP want's to test streams, fs or http modules in the browser, the OP could use browserify to require those modules. However, modules really tightly coupled to Node.js would/should be mocked and the implementation should be tested (which then would be working in the browser if mocked properly)
  • Paul Mougel
    Paul Mougel over 10 years
    Indeed. I believe OP's question was more of: "How do I test Node.js scripts while having the nice output that Mocha for browser has?"
  • Henrik Andersson
    Henrik Andersson over 10 years
    Might be! I have no idea! :D The OP seems to be away! Just be replicating the example he gave in the question, I believe this is what he asked for, but I have no idea! :)
  • whitfin
    whitfin over 10 years
    Basically what @PaulMougel just said, I was hoping for a simple way to generate a HTML report for tests (for displaying the latest tests on a screen for example).
  • Tom
    Tom over 10 years
    What about using a reporter like the JSON one and then having a simple JavaScript that interprets and visualizes the results? Is there anything out there for this already? I basically just want to run the command via terminal and view the results on a web page for easier reading than through the terminal (even though I love the airplane landing report visual). The Doc reporter is nice for an overview of what you're testing, but I don't see where it shows the actual results of any tests. Maybe I'm doing it wrong.
  • taco
    taco about 9 years
    @Tom You probably need to "view source" for XML output as the HTML entities are not encoded, so they're treated like HTML tags.
  • forzagreen
    forzagreen almost 7 years
    The doc reporter outputs an HTML representation of your test cases. It's not showing the results of your tests.