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.
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.
And the following tree structure:
index.html
Disclaimer: I've blatantly forgone all kinds of best practices but just to point you in the right direction.
test/my_something_spec.js
Serving this up with a simple python server
python -m SimpleHTTPServer 8080
from the root and visitlocalhost:8080
will give you a nice and failing test. And running mocha from the terminal will give you the same output, thatexpect
isn't defined.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:
Initialize the directory that will hold all of your tests. Always call it "test":
Edit and/or create some files:
I use Chai. The same chai.js file will be used in both tests.
After creating/editing the files, run the tests via command-line:
...or point your browser at ./test/index.html.
File contents:
Add Chai and your source that you want to test into test/index.html:
Make your tests compatible with command-line and browser
You try to use the
html
reporter, which throws when you try to use it in Node:Per the Mocha documentation (and relevant issue in Github), the
html
reporter 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.