Introduction
In this article, we shall set up a Nodejs project with TDD(Test Driven Development) using mocha (Test runner) and chai (Test Suite).
Let’s jump right in!
Initializing a new project
Create a new project directory called TDD and run npm init -y
mkdir TDD
cd TDD/
npm init -y
npm init -ycreates aNodejsproject with apackage.jsonwith all defaults filled out.
Add mocha and chai dev dependencies
Add mocha and chai development dependencies
npm install -D mocha chai
-Dflag saves the two dependencies underdevDependenciesin apackage.jsonfile at the project root. Installation of the two dev dependencies creates apackage-lock.json, a “cache” of the dependencies. This file is autogenerated and should not be edited.
Write our first test case
This won’t exactly be a test case but a dummy test case to get a glimpse of how to set up things.
- Create a source directory named
src, as the convention. All our project source files will go here. - Create a
__test__directory at the project root. - Inside the
__test__directory, create a new file nameindex.spec.js, the.spec.jsis a convention to differentiate the tests and regular project source. - Inside
src/create anindex.jsfile. - Let’s add a dummy test case:
Import
chaidependency inside. We shall be usingassertfunction to do the assertions.chaioffersshouldandexpectfunctions for doing more complex assertions
const { assert } = require('chai')
// more code here:
When using chai/mocha, we call describe function, pass in a description of the test and a callback function which is gets called by the mocha test runner.
const { assert } = require('chai')
describe('#Test square function', function() {
// test cases go here
} )
- Lets add a test case inside the
describecallback function.
const { assert } = require('chai')
describe('#Test square function', function() {
// test cases go here
it('squares a number and return a value', function() => {
const sq = square(4)
assert(sq === 16, "squar of 4 is 16")
})
} )
- Update the
package.jsonunderscripts, add atestscript.
{
// possible properties ommited
"scripts" : {
"test": "mocha"
}
}
Run the test:
npm test
The test fails because we don’t have the square function implementation yet.
- Let’s create a function that squares a number and returns the value.
const square = (num) => num ** 2
module.exports = square
Run the tests once more
npm test
The test passes.
mocharuns any test files under thetestdirectory
Mocha and Chai make testing async and Promises much easier. Let’s explore more
Async and Promises
Let’s add a function that times out after 6000ms to mimic a delay as in an HTTP request inside src/index.js
const fetchAuth = () => {
return new Promise((reject, resolve) => {
setTimeout(() => {
const data = JSON.stringify({auth: true: token: 'e66d515e-6cbe-46d0-9f22-8705a17b5b6d'})
resolve(data)
}, 6000)
})
}
module.exports = fetchHeroes
- Add a new test case. One may have a single
describeor manydescribefunctions within every single file.
describe('', function() {
it('Fecthes auth and an token', async function() {
const data = await fetchAuth()
const auth = JSON.parse(data)
assert(auth.auth === true, "auth property is true")
assert(typeof(data.token) === 'string')
})
})
Summary
Mocha and Chai provide a way to write and run unit tests. Mocha is the test runner while chai is the test suite providing:
expectshouldassertfunctions to perform assertions
To learn more about Mocha and Chai, check out their docs: https://mochajs.org/
and https://chaijs.org