• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / Getting Started With Unit Testing In Node.JS

Getting Started With Unit Testing In Node.JS

January 7, 2015 by Rana Ahsan Leave a Comment

unit-test-nodejs

I don’t remember any unit test frameworks for JavaScript environment when I first became familiar with this language(around 2008). A lot changed since then. JavaScript took over back-end(NodeJS) too and many other revolutionary libraries/frameworks are now available.

Assuming you are already familiar with NodeJS and have written code for a while, today I am going to share about start performing unit testing In NodeJS application. Just to introduce you about the alternatives, here are two different choices, both of which are very much popular among NodeJS developer community:

  1. Jasmine: A standalone BDD based testing framework that works for both client(browser) and server-side(nodejs) JavaScript. It also includes easy to understand documentation with code snippets.
  2. Mocha With Chai: Mocha is the test runner, a feature rich JavaScript testing framework for both browser and NodeJS. For including the test case, we can have a variety of assertion library choices. Most(and me too) choose to use chai, which have both TDD and BDD based assertion support.

I started with ‘mocha with chai’ without any specific reason and haven’t experienced jasmine yet. So, this tutorial is going to reflect my choice. In case you are experienced with both and have something to share about good/bad part, I will love to hear!

Installing:

You can add the following dependencies in your package.json file and run “npm install” for getting them installed:

"devDependencies": {
     "chai"         : "*",
     "mocha"        : "*"
}

Alternatively, you can just run the npm install commands:

$npm install chai --save
$npm install mocha --save

This will install the modules and add in the package.json file as well.

Write Our First Test Case:

Now, lets create a sample test script helloTest.js and write the following codes:

var expect   = require("chai").expect;
describe("ClassName", function(){
    describe("MethodName", function() {
        it("Description of the case we are testing", function () {
            expect(true).equal(true);
        }); 
    });
});

As we will be use the Behavior driven approach, lets import ‘expect'(or ‘assert’, if you want to do it in classical TDD style). We don’t need to import anything for mocha as mocha itself will run the scripts and thus will provide the import automatically.

Now, explain the tests in three different nested section, class level, method level and test case level. A class can contain several methods, thus several nested ‘describe’ section, and a method can have several ‘test cases’ to verify edge cases/behaviors of the methods.

Sure, the currently given test case is a hard-coded one to make it pass(or make one of them false to fail the test deliberately).

Running The Test Case:

Now its time to run our test case. Its super easy, just run the ‘mocha’ command.

$mocha

Hola! It should work fine and you should see some output with green marks, that means success! Here is an example screenshot with few more test cases:

mocha test output

Extra Tips:

As you just ran your first test, you can go ahead to add few more. However, I would like to add two simple tips that will help you be one step ahead.

Add a test script on package.json: You should have a set script set up with in package.json, something like below:

"scripts": {
        "test": "mocha"
    }

After this, you can run more generic ‘npm test’ command to run your tests. It’s also a standard, such as travis-ci will run this command automatically while building your repo. Moreover, it helps you have a more generic test setup so that in case you change your test libraries/environment,(with change in package.json only) same command can be used to run tests without breaking from outside.

Set up your project for scan all sub-directories too: By default, mocha will run the test scripts which are on current directories, but won’t for sub directories. It can be easily fixed by adding a new file named ‘mocha.opts’ and adding ‘recursive’ option in it as below:

--recursive

Final Words:

I have liked this BDD approach as seems more readable. And mostly, both worked very nicely for me. Tor read more about the other apis available, read the official chaijs documentation on bdd api.

Let me know what you think of it or have anything to suggest/share/feedback via commenting. Lets not ship even a single method without unit test. Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: javascript, nodejs, unit-test

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • Getting Started With UDP Programming in Java
    Getting Started With UDP Programming in Java
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023