Unit Testing in Node

Writing unit tests in Node is very easy, we are going to use 2 tools for doing that: Mocha and Chai.

Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun

https://mochajs.org/

Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.

https://www.chaijs.com/

First of all, make sure you have installed Node in your computer, you can get it here: https://nodejs.org

In your workspace folder, run the next command to init a node package, and complete the requested parameters.

npm init

Run the following command to install Mocha and Chai as a dev dependency

npm install --save-dev mocha chai

Let’s write a simple function that adds 2 numbers

const add2Numbers = (x, y) => {
return x + y;
};

Let’s write the test for that function

// First we have to require chai
const chai = require("chai");


describe("add2Numbers()", () => {
// Description of the test
it("should add 2 numbers", () => {
const x = 1;
const y = 2;

const sum = x + y;

const sumByFunction = add2Numbers(x, y);

// Our assert function
chai.expect(sumByFunction).to.be.equal(sum);
});
});

Next step is to run our tests, go to package.json, and add the «directories» property if not set already. Inside directories, we add another key named «test» that will have the value of the directory where we are saving our test files. Also, we need to add our test script, that will be just «mocha».

package.json
{
.
.
.
"directories": {
"test": "test"
},
"scripts": {
"test" : "mocha"
}
.
.
.
}

So far, our project structure should look like this.

src
- package-lock.json
- package.json
- tests
- - example.test.js

We do the tests running the next command

npm test

The output should look like this

   mocha 
add2Numbers()
✓ should add 2 numbers
1 passing (11ms)

So far so good! Now you know how to write tests in Node.

You can find the code here https://github.com/samosunaz/node-tests

Anuncio publicitario

Deja una respuesta

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Salir /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Salir /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Salir /  Cambiar )

Conectando a %s