How to Write a Library for Node.js and Browser with Mocha Unit Tests
Mocha is a test framework for JavaScript, it provides Node.js and browser versions. Assume we implement a JavaScript library and we want to run unit tests automatically. And also, we want that it could be used in Node.js and browsers. We can use following methods to do that.
This example files structure look like this:
1 | src\md5.js |
Or refer to js-md5.
Installation
Install mocha package to your project.
1 | npm install mocha --save-dev |
If you do not initialize npm project, you can create it at first:
1 | npm init |
The package.json
should look like this:
1 | { |
Export
We have to detect the environment is in Node.js or browser. Assume we implement a md5 fundtion:
1 | ;(function(root, undefined) { |
Write Unit Tests
Create a test file, eg. tests/test.js
and start to write our unit tests. Eg.
1 | describe('less than 64 bytes', function() { |
Test
Node.js Test File
We create the other file for preparing to run unit test. Eg. node-test.js
and add following code:
1 | md5 = require('../src/md5.js'); |
We export the methods which we used in unit test to global variables.
Run Test
We can run this command to test:
1 | mocha node-test.js |
We can add this command to package.json
1 | { |
Now, we can run tests by:
1 | npm test |
And we can see the results like this
Run in Browsers
If you also want to run in browser, you can create a test page like this:
1 |
|
And you can open web page in browsers. You will see:
Further Reading
How to Measure JavaScript Code Coverage With jscoverage
Node.js - How to Integrate Travis CI with GitHub