Using Mocha and Chai for unit tests in Node JS projects

ref – https://ubuverse.com/introduction-to-node-js-api-unit-testing-with-mocha-and-chai/
https://scotch.io/tutorials/test-a-node-restful-api-with-mocha-and-chai

https://gist.github.com/yoavniran/1e3b0162e1545055429e#mocha
https://gist.github.com/yoavniran/1e3b0162e1545055429e#chai

Creating the Directory

mkdir mocha-chai-demo
cd mocha-chai-demo

Setting up the package.json

in directory /mocha-chai-demo:

> npm init

use defualt for all the options.
You will then have a package.json file created.

package name: (mocha-chai-demo) tdd-for-node
version: (1.0.0)
description: test driven dev for node
entry point: (index.js)
test command:
git repository:
keywords: tdd chai mocha node js
author: ricky
license: (ISC)
About to write to /Users/xxxxxxxxx/Desktop/mocha-chai-demo/package.json:

{
“name”: “tdd-for-node”,
“version”: “1.0.0”,
“description”: “test driven dev for node”,
“main”: “index.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1″
},
“keywords”: [
“tdd”,
“chai”,
“mocha”,
“node”,
“js”
],
“author”: “ricky”,
“license”: “ISC”
}

Is this ok? (yes) yes
EPCNSZXW0324:mocha-chai-demo rickytsao$ ls
package.json

Open it with text editor by typing:

open -a TextEdit package.json

and you’ll see your typical specs laid out for your node project.

Whenever you run the project, usually people would do “nodex index.js”. But it can get annoying. So instead, we can shortcut it with start. So next time, all you gotta do to start the server is to type: npm start

You should also edit the test script for mocha.

Under scripts, the value for the key “test” should be: “mocha –recursive”

Implementing the server

in directory /mocha-chai-demo:
> touch index.js

Then copy the code below into the index.js

That file will run as our server.

Then run node index.js to see the server in action

If you were to run the app:

> node index.js

You’ll see the confirmation messages.

Open up a browser, type: http://localhost:8080/colors
you’ll get {“results”:[“RED”,”GREEN”,”BLUE”]}

Creating the tests

The recommended way to organize your tests within your project is to put all of them in their own /test directory.
By default, Mocha checks for unit tests using the globs ./test/*.js and ./test/*.coffee. From there, it will load and execute any file that calls the describe() method.

In mocha-chai-demo:

> mkdir test
> cd test

you should now be in /mocha-chai-demo/test
> touch test.js

then copy the below test code

Save the file.

Then in the test directory, just type:

> npm test

You’ll see that we have 4 passed tests.

Details

ref – http://chaijs.com/api/bdd/

Expect

The BDD style is exposed through expect or should interfaces. In both scenarios, you chain together natural language assertions.

The should style allows for the same chainable assertions as the expect interface, however it extends each object with a should property to start your chain. This style has some issues when used with Internet Explorer, so be aware of browser compatibility.

Differences between expect and should

First of all, notice that the expect require is just a reference to the expect function, whereas with the should require, the function is being executed.

The expect interface provides a function as a starting point for chaining your language assertions. It works on node.js and in all browsers.

The should interface extends Object.prototype to provide a single getter as the starting point for your language assertions. It works on node.js and in all modern browsers except Internet Explorer.

Different ways of creating Objects, Object literal vs Object instances

Object.create()

This method creates a new object extending the prototype object passed as a parameter.

var b = {}

This is equivalent to Object.create(null) method, using a null prototype as an argument.

Using function constructor with new

es6 classes

Singleton pattern

literal vs instances

https://www.internalpointers.com/post/object-literals-vs-constructors-javascript

You have just created a JavaScript object called Website.
The main difference here is what you can do with it.
With the constructor function notation you create an object that can be instantiated into multiple instances with the new keyword

while the literal notation delivers a single object, like a singleton.

MergeSort

How it recursively goes from array to single elements

recursive divide and conquer on arrays

Quick sort version

The divide and conquer recursion on an array occurs when we have dubbed a mid,
then recursively go into the left side of the array. Then, the right side. We leave the middle element.

Thus we apply recursion on

  • low to (mid-1)
  • (mid+1) to high

But how?

1) Print (process) if low == high. This means we have reached a single element.
2) We are at multiple element array. We calculate the mid.
3) recurse into the left array.
4) print the mid.
5) recurse into the right array.

Let’s go into an example.

Say we have an array with 1 to 9. Indexed from 0 to 8. The concept of recursive divide and conquer is that we calculate a pivot first. The pivot is calculated to be somewhere in the middle of the array, then the left and right array are recursively processed.

For simplification purposes, we want to keep things simple. So let’s calculate the pivot such that it is:
floor of (low + high)/2

low: 0
high: 8

pivot = floor(4) = 4, we’ll print this pivot AFTER we process the left array

Our pivot will be printed after all the left array is processed.

Then we recursively process the left array.

low: 0
high: 3

pivot = floor( 0 + 3 /2 ) = 1, we’ll print this pivot AFTER we process the left array

left array is divAndCon(0, 1-1)

So moving on…we process the left array.

It happens that the left array is only an element. We notice that low == high. Under this case, we know that we have reached the element, and thus simply print it (do whatever processing…).

Now we pop back to the previous array. Since we’ve processed the left array of [1], we need to print the mid, which is index 1, element 2. Then we move on to process the right array [3,4]

right array is divAndConq(2,3)

Notice the array we’re processing is [3,4] where:

low: 2
high: 3
mid = floor of (3 + 2 ) / 2 = 2, we’ll print this pivot AFTER we process the left array

left array is divAndCon(2, 2-1) or divAndCon(2, 1)

When we reach to divAndConq(2,1) we see that low > high is false. Thus, we don’t do anything and just return

Once we return, we need to print the the pivot, which is element 3 at index 2.


Then process the right array, which is divAndCon(2+1,3), divAndConq(3,3)

divAndConq(3,3), we see that low == high, and we print (process)

So as you can see, this is how each element is printed (processed) from the beginning to end in a recursive fashion on an array.

Source Code

output

Using divide and conquer to loop

output

MergeSort version

The difference is that the recursion in mergesort does not leave out the mid element. It includes the mid element as part of the right array. Thus, that’s why we use Math.ceil when we divide the array. Thus the recursion is applied on

  • low to (mid – 1)
  • mid to high

We want to drill down to the single element itself, which is when low == high. Then we simply return it. The merge function then proceeds to calculate and sort the returned single elements in 2s. Sorting first, 2 elements. Then the next merge call will sort 4 elements. Then sort 8 sorts, and so on.

output

Futher study

If you want to reverse the display of the array, simply reverse your recursion like so:

This way, you look at the high end first, which is the upper half. Then the next recursion will go upper half. so on, and so on, until you hit the last element first.

JS classes support 3 kinds of methods

https://scotch.io/tutorials/better-javascript-with-es6-pt-ii-a-deep-dive-into-classes

review:

Javascript Prototype

Class Constructors

Static methods

Static methods are methods on the constructor function itself, which are not available on instances of the class.
You define them by using the static keyword.

Prototype methods

Any method that isn’t a constructor or a static method is prototype method. The name comes from the fact that we used to achieve this functionality by attaching functions to the .prototype of functions-as-constructors: