Today I’ll be talking about this very interesting tool I encountered in preparation for Andela boot camp. In the course of the boot camp challenge and working with Test Driven Development(TDD), one of the awesome tools I’ve had to familiarize myself with is Mocha.
What is Mocha?
Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun.
How To Install Mocha with Npm
Installing globally:
1$ npm install --global mocha
Install as dev dependency:
1$ npm install --save-dev mocha
Set up test script in package.json
1"scripts": {2 "test": "mocha"3 }
Basic Mocha Test
In your editor
1var assert = require('assert');2describe('Array', function() {3 describe('#indexOf()', function() {4 it('should return -1 when the value is not present', function() {5 assert.equal([1,2,3].indexOf(4), -1);6 });7 });8});
Back in the terminal:
1$ npm test23 Array4 #indexOf()5 ✓ should return -1 when the value is not present678 1 passing (9ms)
Chai
What is Chai?
Chai is a BDD / TDD assertion library for nodejs and the browser that can be delightfully paired with any javascript testing framework.
Assertion Types
Chai has several interfaces that allow the developer to choose the most comfortable namely:
1chai.should();2foo.should.be.a(‘string’);3foo.should.equal(‘bar’);4foo.should.have.lengthOf(3);5tea.should.have.property(‘flavors’).with.lengthOf(3);
1var expect = chai.expect;2expect(foo).to.be.a('string');3expect(foo).to.equal('bar');4expect(foo).to.have.lengthOf(3); expect(tea).to.have.property('flavors').with.lengthOf(3);
1var assert = chai.assert;2assert.typeOf(foo, 'string');3assert.equal(foo, 'bar');4assert.lengthOf(foo, 3);5assert.property(tea, 'flavors');6assert.lengthOf(tea.flavors, 3);
Conclusion
Testing is a very vital convention software developers must integrate into their project development process. While advising based on my experience, I will suggest Javascript developers should consider using Mocha when choosing a test framework as it is not only simple, it also has an amazing support.
Thank you for reading.
This article was originally posted on Medium