JavaScript
Testing
Mocha
Chai
Published on: Dec 24, 2024
-
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 iex -D mocha chaiInstall Mocha and Chai as development dependencies.
-
index.test.js const { expect } = require('chai');const { getHelloMessage } = require('./index');describe('getHelloMessage()', () => {it('should return "Hello, world!"', () => {expect(getHelloMessage()).to.equal('Hello, world!');});});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
-
{"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.1.2","mocha": "^11.0.1"}}
Add test script to
package.json
. -
Terminal window npm testRun the test.
Terminal output getHelloMessage✔ should return "Hello, world!"1 passing (3ms)