paint-brush
How to run Mocha/Chai unit tests on Node.js appsby@BuddyWorks
41,563 reads
41,563 reads

How to run Mocha/Chai unit tests on Node.js apps

by BuddyApril 20th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

We’ll start with creating a simple <a href="https://hackernoon.com/tagged/nodejs" target="_blank">Node.js</a> application, just like we usually do. The subsequent part of this article will explain how to write, run, and automate tests with BuddyWorks.

Company Mentioned

Mention Thumbnail
featured image - How to run Mocha/Chai unit tests on Node.js apps
Buddy HackerNoon profile picture

Creating a Hello World website with Node.js

We’ll start with creating a simple Node.js application, just like we usually do. The subsequent part of this article will explain how to write, run, and automate tests with BuddyWorks.

Install Node.js

If that’s the first time you work with Node.js, install the npm manager first: nodejs.org/en/download/package-manager

Install NPM and Mocha

Create a directory for the application:

mkdir myapp && cd myapp

Now, npm should be initialized. We’ll use it in order to create a package.json with the Mocha framework:

npm init

You will be asked for the application’s details. Type the following:

  • name: hello-world
  • entry point: app.js
  • test command: ./node_modules/.bin/mocha This framework will be used for testing the application

Confirm the rest of the values by hitting enter.

Create Hello World with Express framework

Express Node.js web application framework will be used for building the app:

npm install express --save

Details of Hello World

Once you already have everything installed, let’s create an app.js file with a simple HTTP server that will serve our Hello World website:

//Load express module with `require` directivevar express = require('express')var app = express()

//Define request response in root URL (/)app.get('/', function (req, res) {  res.send('Hello World')})

//Launch listening server on port 8080app.listen(8080, function () {  console.log('App listening on port 8080!')})

Run the app

Now, the application is ready to launch:

$ node app.js

Go to: http://localhost:8080/ in your browser to view it.

Configuring unit tests with Mocha and Chai

Each single application should be tested before the deployment to the server, especially, if it’s a welcome site that creates the first impression. Here, we will use Mocha as the test running framework, and Chai as the assertion library.

Install Mocha and Chai

Make sure to add Mocha and Chai packages to the package.json:

npm install mocha --savenpm install chai --save

Add a test file

Now, it’s time for defining our first test…

Like what you read? Check out the full guide here!