To write unite tests in node js you nee to install jest package.
After installing the package create a js file with name like abc.test.js. Filename should always contain .test.js in the last of file name then it will be identified by jest framework to execute added unit tests.
In this example I have a file run.js containing functions and run.test.js file containing unit tests of the functions.
To run unit tests run a command npm run test this will run all added unit tests.
run.js
data = [
{
id: 1,
name: "Pedro"
},
{
id: 2,
name: "John"
},
{
id: 3,
name: "Vitor"
}
]
function concat() {
return (obj) => {
obj.id_name = obj.id + " - " + obj.name;
return obj;
}
}
function addition(n1,n2) {
return n1+n2;
}
module.exports = {
concat,
addition
}
run.test.js
const model = require('./run');
describe(`concat`, () => {
test(`GIVEN an array contains an object where id is 10 and name is Lucky,
WHEN function is called,
THEN it should return an additional key id_name containing 10 - Lucky`, () => {
//GIVEN
let data = [
{
id: 10,
name: "Lucky"
}
]
//WHEN
const response = data.map(model.concat());
//THEN
expect(response[0]['id_name']).toBe('10 - Lucky');
})
});
describe(`addition`, () => {
test(`GIVEN two numbers 10 and 20,
WHEN function is called,
THEN it should return 30`, () => {
//GIVEN
const n1 = 10;
const n2 = 20;
//WHEN
const result = model.addition(n1, n2);
//THEN
expect(result).toBe(30);
})
})