CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • 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
Home Development Getting Started With Unit Testing In Node.JS

Getting Started With Unit Testing In Node.JS

Rana Ahsan January 7, 2015 Leave a Comment


 Getting Started With Unit Testing In Node.JS    

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 🙂

Related

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

About Rana Ahsan

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

Leave a Reply Cancel reply

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

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
  • Utilizing Config File In C#.NET Application
  • Generate HTTP Requests using c#
  • How To Work With Codeigniter Caching In PHP
  • Using Supervisord Web Interface And Plugin
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • LinQ To SQL Database Update Operations In C#

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • S. Chalisque on PHP HTML5 Video Streaming Tutorial
  • Armorik on Generate HTTP Requests using c#
  • iswaps on PHP HTML5 Video Streaming Tutorial
  • TAKONDWA on PHP HTML5 Video Streaming Tutorial
  • rorenzo on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2022 · CodeSamplez.com ·

Copyright © 2022 · Streamline Pro Theme on Genesis Framework · WordPress · Log in