Learning JavaScript Testing Quickly with Mocha, Chai, and Sinon

Learning JavaScript Testing Quickly with Mocha, Chai, and Sinon

Learn to write unit tests with Mocha Chai and Sinon as well as learning how to TDD the right way. ... You will learn how to use Mocha, Chai and Sinon together to test your Javascript code giving

Originally published by  Isa Levine  at dev.to

Recently, I had the opportunity to complete a take-home coding challenge that required me to include JavaScript tests with my solution. I will freely admit that I am still learning the ins-and-outs of testing, and that a big part of the battle is knowing what to test. These notes are not intended as a primer on testing generally—instead, I wanted to share the commands and syntax needed to get up-and-running quickly, and get some unit tests written.

So what are we testing here?

The challenge involved building a class, FlavorRanker, that takes in a text file to parse and returns a ranking of most popular flavors. The parsed rankings are stored in a property, this.flavorObj, that is initialized empty, and is filled after running the class function parseTextFile(). Here’s a snapshot of a simplified version:

// FlavorRanker.js

class FlavorRanker { constructor() { this.flavorObj = {}; }

parseTextFile() {    
// fill in this.flavorObj with pairs like “grape”: { “points”: 5 }
}

} exports.FlavorRanker = FlavorRanker;

With this class, there’s a few things we can test right away:

After an instance of FlavorRanker is created, does its this.flavorObjproperty exist?

At certain points, is this.flavorObj empty—or has parseTextFile()successfully added name-value pairs to it?

Has parseTextFile() been called—and has it been called exactly once?

Not the most robust tests, but they’ll introduce us to some essential JavaScript testing syntax from frameworks Mocha, Chai, and Sinon!

Wait, why are we covering three things at once?

Short answer: because they work so well together! Briefly, here’s what each of them will do for us:

  • Mocha - A JavaScript test runner and framework that provides a describe()/it() syntax for testing assertions. This will be the thing specified in your package.json file under “scripts”: { “test”: “mocha” }.
  • Chai - A library that adds extra readability to JavaScript test assertions. Supplants the Node.js default assert() syntax with expect().to.be, and lots of chain-able options.
  • Sinon - A library that provides spies that “watch” functions and can detect when they’re called, what arguments are passed to them, what is returned, etc. (Sinon provides a lot more than that, but we’ll stick with just spies for this post.)

Setup

To include these packages in your project, use the following commands:

$ npm install -g mocha - this will install Mocha globally (not just in your current project), and give you access to $ mocha commands in your terminal. (This guide won’t cover that.)

$ npm install chai - this will install Chai locally.

$ npm install sinon - this will install Sinon locally.

You will also want to create a /test directory, and a test.js file inside that directory:

test
|-- test.js

Finally, in your package.json file, check your “scripts” section to make sure “test” is set to “mocha”:

// package.json

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

Let’s write some tests!

Importing

Let’s load some specific tools into our tests. We’ll be using Chai’s export, Sinon’s spy, and the FlavorRanker class from above:

// test.js 

const expect = require('chai').expect; const spy = require('sinon').spy; const FlavorRanker = require('../flavorRanker.js').FlavorRanker;

Use describe() to organize tests and create contexts

Mocha allows us to write tests by nesting describe() functions within each other. This StackOverflow discussion goes into some of the when/why/how of organizing tests, but here’s the gist:

describe(“String with test description”, function() { … } )

NOTE: This article covers why you DON’T want to use arrow functions instead of function() {} in Mocha.

You can nest these as deeply as you want—just be aware that each one establishes a new context, and that variable scoping applies here as expected:

describe('Generic test name', function() {
    // variable flavorRanker does NOT exist in this context.

describe('FlavorRanker class', function() {
    const flavorRanker = new FlavorRanker;

    describe('flavorRanker instance', function() {
        // variable flavorRanker DOES exist in this context.
    });
});

});

Use it() to declare a single test

Within a describe() context, each it() function describes a single test. The syntax is:

it(“String with test description”, function() { … } )

Here are two tests ensuring that a newly-created instance of FlavorRanker has a this.flavorObj property, and that it’s an empty object:

describe('flavorRanker instance', function() {

        it('should have a flavorObj property that is an object', function() {
            // testable assertion
        });

        it('flavorObj should be empty', function() {
            // testable assertion
        });

Chai: expect()

Chai shines because it makes writing readable tests so simple. Here’s the syntax for expect():

expect(foo).to..._____ …

In the blanks, you can add a host of chain-able functions that create the testable assertion. Here’s how we can write expect() functions for the two tests above:

describe('flavorRanker instance', function() {

        it('should have a flavorObj property that is an object', function() {
            expect(flavorRanker.flavorObj).to.be.an('object');
        });

        it('flavorObj should be empty', function() {
            expect(flavorRanker.flavorObj).to.be.empty;
        });

The tests will check exactly what they say: is flavorRanker.flavorObj an object, and is it empty? Here’s the terminal output from running $ npm test:

  Generic test name
    FlavorRanker class
      flavorRanker instance
        ✓ should have a flavorObj property that is an object
        ✓ flavorObj should be empty

Sinon: spy()

Finally, we can use Sinon’s spy() function to assign a variable to “watch” for certain behaviors, like the function being called or returning a value. To create a spy:

const spyName = spy(object, “functionName”)

For our tests, we’ll create a spy for flavorRanker’s parseTextFile() method:

        describe('flavorRanker instance', function() {
            const parseTextFile = spy(flavorRanker, "parseTextFile");

        it('should have a flavorObj property that is an object', function() {
            expect(flavorRanker.flavorObj).to.be.an('object');
        });

        it('flavorObj should be empty', function() {
            expect(flavorRanker.flavorObj).to.be.empty;
        });

    });

And now, we can write tests using Chai’s syntax to check if it’s been called exactly once:

        describe('flavorRanker instance', function() {
            const parseTextFile = spy(flavorRanker, “parseTextFile");

// spy detects that function has been called
flavorRanker.parseTextFile();

// checks that function was called once in this test’s context
        it('flavorRanker.parseTextFile() should be called once', function() {
            expect(parseTextFile.calledOnce).to.be.true;
        });

    });

Now, when we run $ npm test again, our terminal shows:

  Generic test name
    FlavorRanker class
      flavorRanker instance
        ✓ should have a flavorObj property that is an object
        ✓ flavorObj should be empty
        ✓ flavorRanker.parseTextFile() should be called once

Perfect!

Conclusion: This is only the beginning!

As I stated in the intro, this writeup is NOWHERE NEAR comprehensive—but for folks like me who are a little daunted by starting to learn JavaScript testing, having just a couple easy-to-use tools can help you get started! Please feel free to leave comments below sharing any other intro-level tips for someone who needs to learn some testing syntax quick!

Originally published by  Isa Levine  at dev.to

===========================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Learn Javascript Unit Testing With Mocha, Chai and Sinon

☞ Svelte.js - The Complete Guide

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ JavaScript: Understanding the Weird Parts

☞ JavaScript: Coding Challenges Bootcamp - 2019

☞ The Complete Node.js Developer Course (3rd Edition)

☞ Angular & NodeJS - The MEAN Stack Guide

☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

☞ Node.js Absolute Beginners Guide - Learn Node From Scratch

javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.