Node Mocha Hooks (Set up and Tear Down)

Posted on Friday, April 17, 2015



As I start developing in node from scratch I want to do it right.  I installed the Node plugin for Intellij and poked at it a bit (the write up is at http://www.whiteboardcoder.com/2015/04/intellij-and-nod.html )
I also set up mocha with chai to do my TDD testing see http://www.whiteboardcoder.com/2015/04/intellij-and-nodejs-setting-up-tdd.html .


I want to see what mocha's equivalent to the JUnit methods setUp() and tearDown().   Basically what methods are available to me in Mocha to set up the environment or variables before running a set of tests and what is there to remove those setups afterwards?




Hooks


It looks like it's actually very simple.  Check out http://mochajs.org/#hooks [1]


For a one time set up that runs once before any test is run, use before.


before(function(){
    console.log(
'Runs once before all test in this file')
})



For a one time tear down that runs once after all tests have run, use after.


after(function(){
    console.log(
'Runs once after all test in this file')
})




To run before each test use beforeEach.


beforeEach(function(){
    console.log(
'Runs before every test in this file')
})


To run after each test use afterEach.


afterEach(function(){
    console.log(
'Runs after every test in this file')
})



Testing it out


Here is some test code I made to show how it works.


var assert = require('chai').assert;

describe(
'Number Testing', function() {

   
var data = {'names':['joe', 'lisa', 'fred']}

    before(
function(){
        console.log(
'Runs once before all test in this file')
    })
    after(
function(){
        console.log(
'Runs once after all test in this file')
    })

    beforeEach(
function(){
        console.log(
'Runs before every test in this file')
    })
    afterEach(
function(){
        console.log(
'Runs after every test in this file')
    })


    describe(
'Testing equality', function() {
        it(
'2 should equal 2', function () {
           
assert.equal(2, 2);
        });
    });

    describe(
'Testing array Size', function() {
        it(
'Array should contain 3 names', function () {
           
assert.equal(data.names.length, 3);
        });
    });
});



Run the test.  (My test is located at test/numbers.test.js


  > mocha test/numbers.test.js



Here is the output






It's as easy as that, nice job mocha guys.


References

[1]        Mocha Hooks
                Accessed 4/2015

No comments:

Post a Comment