{"id":19853,"date":"2015-05-23T22:43:51","date_gmt":"2015-05-23T17:13:51","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=19853"},"modified":"2015-06-02T01:12:44","modified_gmt":"2015-06-01T19:42:44","slug":"introduction-to-mocha-part-1","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/introduction-to-mocha-part-1\/","title":{"rendered":"Introduction To Mocha [Part-1]"},"content":{"rendered":"<p><a href=\"#\">\u00a0<\/a><\/p>\n<h1 id=\"top\" style=\"text-align: center\">Introduction To Mocha<\/h1>\n<blockquote><p>Recently I have started learning MochaJs for unit testing of my NodeJs application. Although \u00a0http:\/\/mochajs.org\/ is very well documented and refine in its own. But that is most respect to Mocha itself. I tried and created lots of example so that it can relate to NodeJs.<\/p><\/blockquote>\n<p style=\"text-align: center\">Before starting further, Clone\/download examples from git repository-\u00a0<a href=\"https:\/\/github.com\/deepakshrma\/test-driven-nodejs-development\">Introduction To Mocha<\/a><\/p>\n<p style=\"text-align: center\"><strong>Table of Contents<\/strong><\/p>\n<ul>\n<li><a href=\"#intro-to-mocha\">Introduction To Mocha<\/a>\n<ul>\n<li><a href=\"#installation\">Installation<\/a>\n<ul>\n<li><a href=\"#npm-install\">NPM Install (npm)<\/a><\/li>\n<\/ul>\n<\/li>\n<li><a href=\"#start-with-mocha\">Starting with mocha<\/a><\/li>\n<li><a href=\"#intro-to-assert\">Introduction to Assertion<\/a><\/li>\n<li><a href=\"#sync-code-testing\">Synchronous code Testing<\/a><\/li>\n<li><a href=\"#async-code-testing\">Asynchronous code Testing<\/a><\/li>\n<li><a href=\"#testing-with-nodejs\">Testing with Nodejs<\/a><\/li>\n<li><a href=\"#error-handling-with-mocha\">Error Handling With Mocha<\/a><\/li>\n<li><a href=\"#error-handling-in-nodejs\">Error Handling In Nodejs Style<\/a><\/li>\n<li><a href=\"#integration-with-hooks\">Integrating With Mocha Hooks<\/a><\/li>\n<li><a href=\"#hooks-in-delails\">Hooks In Details<\/a><\/li>\n<li><a href=\"#desc-hooks\">Describe Hooks<\/a><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h1 style=\"text-align: center\"><a id=\"intro-to-mocha\"><\/a>Introduction To MochaJs<\/h1>\n<p>Mocha is a JavaScript testing framework, which runs on NodeJs and browser. It is mostly use to test synchronous and asynchronous JavaScript code. Easy to use and it&#8217;s also provides you simple test case results.<\/p>\n<ul>\n<li>\n<h3><a id=\"installation\"><\/a>Installation<\/h3>\n<\/li>\n<\/ul>\n<p>This library is available on <strong>npm<\/strong>. Install with <strong>npm<\/strong>:<\/p>\n<ul>\n<li>\n<h4><a id=\"npm-install\"><\/a>NPM Install(npm)<\/h4>\n<\/li>\n<\/ul>\n<p>[bash]<\/p>\n<p>$ npm install -g mocha<\/p>\n<p>[\/bash]<\/p>\n<p>Above command will install mocha globally to your npm environment.<\/p>\n<ul>\n<li>\n<h4><a id=\"start-with-mocha\"><\/a>Starting with mocha<\/h4>\n<\/li>\n<\/ul>\n<p>When you work on TDD(Test Driven Development), You need to take care of your project structure. Where you will put your test cases on all. I have basically created a test folder where i put all test cases.<\/p>\n<p>[bash]<\/p>\n<p>$ mkdir test<\/p>\n<p>[\/bash]<\/p>\n<p>Once you create a testing folder, Just create your first mocha test case. ie. <strong>testing.js<\/strong> It would be something like<\/p>\n<p>[js]<\/p>\n<p>\/\/1-start-with-mocha.js<br \/>\nvar assert = require(&quot;assert&quot;)<br \/>\ndescribe(&#8216;String&#8217;, function () {<br \/>\n    describe(&#8216;#substring()&#8217;, function () {<br \/>\n        it(&#8216;should return -1 when the value is not present&#8217;, function () {<br \/>\n            assert.equal(-1, &#8216;True Developer!! Testing is hardest thing to do&#8230;&#8217;.indexOf(&#8216;developer&#8217;));<br \/>\n        });<br \/>\n    });<br \/>\n});<\/p>\n<p>[\/js]<\/p>\n<p>Output would be: String #substring() \u2713 should return -1 when the value is not present<\/p>\n<h5 style=\"text-align: center\">Explanation\u00a0of Previous Code<\/h5>\n<p><strong>describe<\/strong> is use to describe different level of block of your code. <strong>it<\/strong> is to specify the test case that you have created.<\/p>\n<ul>\n<li>\n<h3><a id=\"start-with-mocha\"><\/a>Introduction to Assertion<\/h3>\n<\/li>\n<\/ul>\n<p>Mocha is very flexible to use any of the assertion library. If it throws error it will work with mocha. There are lots of assertion library available in cloud. I personally prefer shouldjs and chaijs. You can use native assertion module of node.<\/p>\n<ul>\n<li>\n<h4>Using NodeJs assert Module<\/h4>\n<\/li>\n<\/ul>\n<p>[js]<\/p>\n<p>var assert = require(&quot;assert&quot;);<br \/>\ndescribe(&#8216;String&#8217;, function () {<br \/>\n    describe(&#8216;#substring()&#8217;, function () {<br \/>\n        it(&#8216;should return -1 when the value is not present&#8217;, function () {<br \/>\n            assert.equal(-1, &#8216;True Developer!! Testing is hardest thing to do&#8230;&#8217;.indexOf(&#8216;developer&#8217;));<br \/>\n        });<br \/>\n    });<br \/>\n});<\/p>\n<p>[\/js]<\/p>\n<ul>\n<li>\n<h4>Using ShouldJs<\/h4>\n<\/li>\n<\/ul>\n<div class=\"highlight highlight-bash\">\n<p>[bash]<\/p>\n<p>$  npm install should &#8211;save-dev<\/p>\n<p>[\/bash]<\/p>\n<\/div>\n<p>[js]<\/p>\n<p>\/\/2-starting-to-shouldjs.js<br \/>\nvar should = require(&#8216;should&#8217;)<br \/>\ndescribe(&#8216;Array&#8217;, function () {<br \/>\n    describe(&#8216;#indexOf()&#8217;, function () {<br \/>\n        it(&#8216;should return -1 when the value is not present&#8217;, function () {<br \/>\n            [1, 2, 3].indexOf(5).should.equal(-1);<br \/>\n            [1, 2, 3].indexOf(0).should.equal(-1);<br \/>\n        })<br \/>\n    })<br \/>\n})<\/p>\n<p>[\/js]<\/p>\n<ul>\n<li>\n<h3><a id=\"sync-code-testing\"><\/a>Synchronous code Testing<\/h3>\n<\/li>\n<\/ul>\n<p>By default javascript environment is sync in nature(Not nodejs \ud83d\ude09 ). When you don&#8217;t callback to test cases, Mocha runs all test cases serially and sequentially.<\/p>\n<p>[js]<\/p>\n<p>\/\/3-synchronous-testing.js<br \/>\nvar should = require(&#8216;should&#8217;)<br \/>\ndescribe(&#8216;Array&#8217;, function () {<br \/>\n    describe(&#8216;#indexOf()&#8217;, function () {<br \/>\n        it(&#8216;Test Case-1: should return -1 when the value is not present&#8217;, function () {<br \/>\n            [1, 2, 3].indexOf(5).should.equal(-1);<br \/>\n            [1, 2, 3].indexOf(0).should.equal(-1);<br \/>\n        });<br \/>\n    });<br \/>\n});<br \/>\ndescribe(&#8216;String&#8217;, function () {<br \/>\n    describe(&#8216;#substring()&#8217;, function () {<br \/>\n        it(&#8216;Test Case-2: should return -1 when the value is not present&#8217;, function () {<br \/>\n            &#8216;True Developer!! Testing is hardest thing to do&#8230;&#8217;.indexOf(&#8216;developer&#8217;).should.equal(-1);<br \/>\n        });<br \/>\n    });<br \/>\n});<\/p>\n<p>[\/js]<\/p>\n<ul>\n<li>\n<h3><a id=\"async-code-testing\"><\/a>Asynchronous code Testing<\/h3>\n<\/li>\n<\/ul>\n<p>Development environment like nodejs, is async in nature. Mocha provides you such design pattern where you can define callback function. Call it when you done with it.<\/p>\n<p>[js]<\/p>\n<p>\/\/4-asynchronous-testing.js<br \/>\nvar should = require(&#8216;should&#8217;)<br \/>\ndescribe(&#8216;Array&#8217;, function () {<br \/>\n    describe(&#8216;#indexOf()&#8217;, function () {<br \/>\n        it(&#8216;Test Case-1: should return -1 when the value is not present&#8217;, function (done) {<br \/>\n            setTimeout(function () {<br \/>\n                [1, 2, 3].indexOf(5).should.equal(-1);<br \/>\n                [1, 2, 3].indexOf(0).should.equal(-1);<br \/>\n                done();<br \/>\n            }, 1000)<br \/>\n        });<br \/>\n    });<br \/>\n});<br \/>\ndescribe(&#8216;String&#8217;, function () {<br \/>\n    describe(&#8216;#substring()&#8217;, function () {<br \/>\n        it(&#8216;Test Case-2: should return -1 when the value is not present&#8217;, function (done) {<br \/>\n            setTimeout(function () {<br \/>\n                &#8216;True Developer!! Testing is hardest thing to do&#8230;&#8217;.indexOf(&#8216;developer&#8217;).should.equal(-1);<br \/>\n                done();<br \/>\n            }, 500);<br \/>\n        });<br \/>\n    });<br \/>\n});<\/p>\n<p>[\/js]<\/p>\n<ul>\n<li>\n<h3><a id=\"testing-with-nodejs\"><\/a>Testing With Nodejs<\/h3>\n<\/li>\n<\/ul>\n<p>In nodejs you mostly deals with async libraries. To show how to use mocha on node, I have created a dummy crud operation on mogoDb using mongoose.js.<\/p>\n<p>[js]<\/p>\n<p>\/\/5-testing-with-nodejs.js<br \/>\nvar mongoose = require(&#8216;mongoose&#8217;);<br \/>\nmongoose.connect(&#8216;mongodb:\/\/localhost\/test&#8217;);<br \/>\nvar Cat = require(&#8216;..\/db\/cat&#8217;);<br \/>\ndescribe(&#8216;Cat Modal&#8217;, function () {<br \/>\n    describe(&#8216;#create()&#8217;, function () {<br \/>\n        it(&#8216;should return cat when cat has created&#8217;, function (done) {<br \/>\n            Cat.find({}).remove(function () {<br \/>\n                var cat = new Cat({name: &#8216;Deepak&#8217;});<br \/>\n                cat.save(function (error, cat) {<br \/>\n                    console.log(&#8216;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&#8217;);<br \/>\n                    console.log(&#8216;%j&#8217;, cat);<br \/>\n                    console.log(&#8216;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&#8217;);<br \/>\n                    done();<br \/>\n                })<br \/>\n            });<br \/>\n        });<br \/>\n    });<br \/>\n});<\/p>\n<p>[\/js]<\/p>\n<ul>\n<li>\n<h3><a id=\"error-handling-with-mocha\"><\/a>Error Handling With Mocha<\/h3>\n<\/li>\n<\/ul>\n<p>The real purpose of testing is to write test cases which can be use in future in case of any modification of the Api without understanding the logic behind it. Here i have given small demonstration how we can handles error in api<\/p>\n<p>[js]<\/p>\n<p>\/\/6-error-handling-with-mocha.js<br \/>\nvar mongoose = require(&#8216;mongoose&#8217;);<br \/>\nmongoose.connect(&#8216;mongodb:\/\/localhost\/test&#8217;);<br \/>\nvar Cat = require(&#8216;..\/db\/cat&#8217;);<br \/>\ndescribe(&#8216;Cat Modal&#8217;, function () {<br \/>\n    describe(&#8216;#create()&#8217;, function () {<br \/>\n        it(&#8216;should fail since cat is already created with name Billi&#8217;, function (done) {<br \/>\n            var cat = new Cat({name: &#8216;Billi&#8217;});<br \/>\n            cat.save(function (error, cat) {<br \/>\n                if (error) {<br \/>\n                    return done(error)<br \/>\n                }<br \/>\n                \/\/   throw error;<br \/>\n                console.log(&#8216;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&#8217;);<br \/>\n                console.log(&#8216;%j&#8217;, cat);<br \/>\n                console.log(&#8216;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&#8217;);<br \/>\n                done();<br \/>\n            })<br \/>\n        });<br \/>\n    });<br \/>\n});<\/p>\n<p>[\/js]<\/p>\n<ul>\n<li>\n<h3><a id=\"error-handling-in-nodejs\"><\/a>Error Handling In Nodejs Style<\/h3>\n<\/li>\n<\/ul>\n<p>In nodejs there you need to define a callback to every single IO Async operation. You can pass callback of mocha to that IO operation. It will work like charm.<\/p>\n<p>[js]<\/p>\n<p>\/\/7-error-handling-in-nodejs-style.js<br \/>\nvar mongoose = require(&#8216;mongoose&#8217;);<br \/>\nmongoose.connect(&#8216;mongodb:\/\/localhost\/test&#8217;);<br \/>\nvar Cat = require(&#8216;..\/db\/cat&#8217;);<br \/>\ndescribe(&#8216;Cat Modal&#8217;, function () {<br \/>\n    describe(&#8216;#create()&#8217;, function () {<br \/>\n        it(&#8216;should fail since cat is already created with name Deepak&#8217;, function (done) {<br \/>\n            var cat = new Cat({name: &#8216;Deepak&#8217;});<br \/>\n            cat.save(done)<br \/>\n        });<br \/>\n    });<br \/>\n});<\/p>\n<p>[\/js]<\/p>\n<ul>\n<li>\n<h3><a id=\"integration-with-hooks\"><\/a>Integrating With Mocha Hooks<\/h3>\n<\/li>\n<\/ul>\n<p>Mocha provide us some predefined hooks like before(), after(), beforeEach(), afterEach(), that can be used on some predefined situation as per user requirement to clean the test cases.<\/p>\n<p>[js]<\/p>\n<p>\/\/8-integrating-with-mocha-hooks.js<br \/>\nvar mongoose = require(&#8216;mongoose&#8217;);<br \/>\nmongoose.connect(&#8216;mongodb:\/\/localhost\/test&#8217;);<br \/>\nvar should = require(&#8216;should&#8217;)<br \/>\nvar Cat = require(&#8216;..\/db\/cat&#8217;);<br \/>\ndescribe(&#8216;Connection&#8217;, function () {<br \/>\n    var tobi = new Cat({name: &#8216;tobi&#8217;})<br \/>\n        , loki = new Cat({name: &#8216;loki&#8217;})<br \/>\n        , jane = new Cat({name: &#8216;jane&#8217;});<br \/>\n    beforeEach(function (done) {<br \/>\n        Cat.remove({}, function (err) {<br \/>\n            console.log(&#8216;collection dropped&#8217;);<br \/>\n            Cat.create([tobi, loki, jane], done);<br \/>\n        });<br \/>\n    })<br \/>\n    describe(&#8216;#find()&#8217;, function () {<br \/>\n        it(&#8216;respond with matching records&#8217;, function (done) {<br \/>\n            Cat.find({}, function (err, res) {<br \/>\n                if (err) return done(err);<br \/>\n                res.should.have.length(3);<br \/>\n                done();<br \/>\n            })<br \/>\n        })<br \/>\n    })<br \/>\n});<\/p>\n<p>[\/js]<\/p>\n<h3>To be continued<strong>&#8230;<\/strong><\/h3>\n<h1><a title=\"&lt;Go 2 Top&gt;\" href=\"#top\">&lt;Go 2 Top&gt;<\/a><\/h1>\n<p><a title=\"contact:me\" href=\"mailto:deepak.m.shrma@gmail.com\">contact:me<\/a><\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u00a0 Introduction To Mocha Recently I have started learning MochaJs for unit testing of my NodeJs application. Although \u00a0http:\/\/mochajs.org\/ is very well documented and refine in its own. But that is most respect to Mocha itself. I tried and created lots of example so that it can relate to NodeJs. Before starting further, Clone\/download examples [&hellip;]<\/p>\n","protected":false},"author":136,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":1},"categories":[1185],"tags":[1832,1835,14,1830,1831,1124,1177,1836,1834,1833],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/19853"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/136"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=19853"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/19853\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=19853"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=19853"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=19853"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}