Get started with Mocha testing
Make a package.json
file if you don't have one yet:
npm init
# just keep pressing enter.
# this will create the file `package.json`
Install your weapons:
npm install --save-dev mocha chai
Make your first test file test/my_test.js
:
/* test/my_test.js */
var expect = require('chai').expect;
describe('my test suite', function () {
it('fails majestically', function () {
expect(3).to.eql(2);
});
});
Update your package.json
to use mocha:
"scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
+ "test": "mocha"
},
Run tests by typing npm test
:
my test suite
1) fails majestically
0 passing (17ms)
1 failing
1) my test suite fails majestically:
AssertionError: expected 3 to deeply equal 2
+ expected - actual
+2
-3
test/test.js:5:18: Context.<anonymous>
Now go write tests that will pass!
describe('test suite', function () {
beforeEach(function() { /*...*/ });
afterEach(function() { /*...*/ });
before(function() { /*...*/ });
after(function() { /*...*/ });
it('a basic test', function() {
/*...*/ });
it('a test with a promise', function() {
return somePromiseObject; });
it('an asynchronous test', function(next) {
if (success) { next(); } else { next(error); }
});
xit('use "xit" for pending tests', function() {
/*...*/ });
});
Also see http://mochajs.org/ - read up on Mocha's API
expect(3).to.eql(2);
expect(obj).to.be.a('string');
expect(obj).to.be.null;
expect(obj).to.be.true;
expect(obj).to.be.false;
expect(obj).to.be.undefined;
expect(list).to.include("item");
expect(list).to.have.length(3);
expect(list).to.have.length.gt(0);
See: http://chaijs.com/api/bdd/ — other expect()
ations
- http://sinonjs.org/ - use Sinon for mocks