mocha test cases in node js example

How to write Mocha test cases in Node.js with example?

As a software developer, testing is an essential part of the development process. In Node.js, Mocha is a popular JavaScript testing framework that allows developers to write test cases for their code. Mocha is flexible, easy to use, and supports both async and sync testing. Here's an example of how to write Mocha test cases in Node.js:

Step 1: Install Mocha

Firstly, install Mocha via npm:

npm install --global mocha

Step 2: Create a Test File

Next, create a test file in your project directory. Let's call it "test.js".

const assert = require('assert');
    
    describe('Array', function() {
      describe('#indexOf()', function() {
        it('should return -1 when the value is not present', function() {
          assert.equal([1,2,3].indexOf(4), -1);
        });
      });
    });

Step 3: Run the Test File

To run the test file, open your terminal and navigate to your project directory. Then run:

mocha

Step 4: View the Results

You should see the results of your test cases:

Array
      #indexOf()
        ✓ should return -1 when the value is not present
    
    1 passing (5ms)

Alternative Way 1: Chai Assertion Library

Chai is another popular assertion library that can be used with Mocha. Here's an example:

const expect = require('chai').expect;
    
    describe('Array', function() {
      describe('#indexOf()', function() {
        it('should return -1 when the value is not present', function() {
          expect([1,2,3].indexOf(4)).to.equal(-1);
        });
      });
    });

Alternative Way 2: Async Testing

Mocha also supports async testing. Here's an example:

describe('File', function() {
      describe('#readFile()', function() {
        it('should read file asynchronously', function(done) {
          fs.readFile('./test.txt', function(err, data) {
            if (err) throw err;
            expect(data.toString()).to.equal('Hello World\n');
            done();
          });
        });
      });
    });

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe