Technologies used
- Node - 23.5.0
- Chai - 5.2.0
- Mocha - 11.2.2
-
Terminal window npm init -yInitialize a new Node.js project in current directory.
-
index.js function getHelloMessage() {return 'Hello, world!';}module.exports = {getHelloMessage}Create
getHelloMessage()
function that will be tested. -
Terminal window npm i -D mocha@11.2.2 chai@5.2.0Install Mocha and Chai as development dependencies.
-
index.test.js const { getHelloMessage } = require('./index');const assert = require('assert');describe('getHelloMessage', () => {it('should return "Hello, world!"', () => {const actualResult = getHelloMessage();assert.equal('Hello, world!', actualResult);});});Create a test file
index.test.js
to testgetHelloMessage()
function.- The
expect
function is used to create assertions in the test cases. - Define a test suite for the
getHelloMessage()
function. Thedescribe()
function is used to group related test cases together, making the test output more organized and readable. - Define a test case for the
getHelloMessage()
function. Theit()
function is used to define a single test case. The first argument is a description of the test case, and the second argument is a function that contains the test logic.
- The
-
package.json {"name": "how-to-test-js-app-with-mocha-and-chai","version": "1.0.0","description": "","main": "index.js","scripts": {"test": "mocha index.test.js"},"keywords": [],"author": "","license": "ISC","devDependencies": {"chai": "^5.2.0","mocha": "^11.2.2"}}Add test script to
package.json
. -
Terminal window npm testRun the test.
Terminal output getHelloMessage✔ should return "Hello, world!"1 passing (3ms)