Write test cases

There’re lots of excellent test frameworks written in Node.js. For example, mocha, jasmine and so on.

We would like to use mocha to write our test cases.

Anyone who wants to know more about Mocha could visit its homepage for more information: mocha.org

  • Install mocha
  1. npm install -g mocha
  • Use assert
  1. var assert = require('assert');

“assert” includes many Node.js modules about assertion, e.g. should.js, expect. Most of this modules are practices on Behavior Driven Development, a.k.a, BDD.

  • Example of assert
  1. describe('Array', function() {
  2. describe('#indexOf()', function() {
  3. it('should return -1 when the value is not present', function() {
  4. [1,2,3].indexOf(5).should.equal(-1);
  5. [1,2,3].indexOf(0).should.equal(-1);
  6. });
  7. });
  8. });

It seems that we have just described a thing using English. Yes, what we are going to do is to describe what the functions in “node-validators” would works like.

Following the examples above, here comes the prototype of our use cases:

  1. var assert = require('assert');
  2. var validator = require('validator-test');
  3. describe('Validator', function () {
  4. describe('#isEmail', function () {
  5. it('should return true when the string is an email address', function () {
  6. if (validator.isEmail('foo@bar.net') !== true) {
  7. throw new Erorr('Validator not right');
  8. }
  9. });
  10. });
  11. });

Type mocha in your terminal, this would run the test.js file in test folder automatically:

  1. mocha

The we will get the result:

  1. Validator
  2. #isEmail
  3. should return true when the string is an email address
  4. 1 passing (6ms)

What’s next? Just write test cases for every functions in “node-validator” in order to cover all.