Unit Testing Tool - Mits10/School_Management_System_Php_Html_Css_JavaScript_From_Scratch GitHub Wiki
Mocha
Introduction
Mocha is an old and widely used testing framework for node applications. It supports asynchronous operations like callbacks, promises, and async/await. It is a highly extensible and customizable framework that supports different assertions and mocking libraries.
Installation
To install it, open command prompt and type the following command:
# Installs globally
npm install mocha -g
# installs in the current directory
npm install mocha --save-dev
How to use Mocha?
In order to use this framework in your application:
- Open the root folder of your project and create a new folder called test in it.
- Inside the test folder, create a new file called test.js which will contain all the code related to testing.
- open package.json and add the following line in the scripts block.
"scripts": {
"test": "mocha --recursive --exit"
}
Example
// Requiring module
const assert = require('assert');
// We can group similar tests inside a describe block
describe("Simple Calculations", () => {
before(() => {
console.log( "This part executes once before all tests" );
});
after(() => {
console.log( "This part executes once after all tests" );
});
// We can add nested blocks for different tests
describe( "Test1", () => {
beforeEach(() => {
console.log( "executes before every test" );
});
it("Is returning 5 when adding 2 + 3", () => {
assert.equal(2 + 3, 5);
});
it("Is returning 6 when multiplying 2 * 3", () => {
assert.equal(2*3, 6);
});
});
describe("Test2", () => {
beforeEach(() => {
console.log( "executes before every test" );
});
it("Is returning 4 when adding 2 + 3", () => {
assert.equal(2 + 3, 4);
});
it("Is returning 8 when multiplying 2 * 4", () => {
assert.equal(2*4, 8);
});
});
});
Copy the above code and paste it in the test.js file that we have created before. To run these tests, open the command prompt in the root directory of the project and type the following command: \
npm run test
Output
What is Chai?
Chai is an assertion library that is often used alongside Mocha. It can be used as a TTD (Test Driven Development) / BDD (Behavior Driven Development) assertion library for Node.js that can be paired up with any testing framework based on JavaScript. Similar to assert.equal() statement in the above code, we can use Chai to write tests like English sentences.
To install it, open the command prompt in the root directory of the project and type the following command:
npm install chai
Example:
const expect = require('chai').expect;
describe("Testing with chai", () => {
it("Is returning 4 when adding 2 + 2", () => {
expect(2 + 2).to.equal(4);
});
it("Is returning boolean value as true", () => {
expect(5 == 5).to.be.true;
});
it("Are both the sentences matching", () => {
expect("This is working").to.equal('This is working');
});
});