MENU
Mocha & Chai
Alexa's Ranking (Mocha): 156,237
Alexa's Ranking (Chai): 246,424
To begin:
> npm init –y> npm i --save-dev mocha chai chai-as-promised> npm test
// package.json//…"scripts": {
"test": "mocha"}
Mocha tests run serially by default, although they can be made to run in parallel too (with the --parallel flag). By default, Mocha looks for the test file named 'test.js' and the test files in the 'test/' directory.
Mocha allows you to use any assertion library other than the 'assert' and 'chai' modules. For instance, you can choose 'expect.js' to use expect() style assertions.Notice below, the syntax is identical to that of Jest, with it() replacing test() and assert() replacing expect().
var assert = require('assert');var chai = require("chai");var chaiAsPromised = require("chai-as-promised");chai.use(chaiAsPromised);chai.should();// dummy databasedb = {
clear: ()=>Promise.resolve(),
save: d=>Promise.resolve(d),
find: d=>Promise.resolve([d,d,d]),}class User{
save(callback){callback();}}// end of dummy databasedescribe('Array', function () {
describe('#indexOf()', function () {
it('should return -1 when the value is not present',()=>{
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
it('should save without error', function (done) {
var user = new User('Luna');
user.save(done);
});});beforeEach(async function () {
await db.clear();
await db.save(['tobi', 'loki', 'jane']);
console.log('testing');});describe('#find()', function () {
after(()=>{
console.log('after all');
});
it('respond with matching records', function () {
return db.find({type: 'User'}).
should.eventually.have.length(3);
});});
D:\demo\mocha-demo>npm run test> mocha-demo@1.0.0 test D:\demo\mocha-demo> mocha
Arraytesting
√ should save without error
#indexOf()testing
√ should return -1 when the value is not present
#find()testing
√ respond with matching recordsafter all
3 passing (9ms)
Mocha tests can run in the browser too.
// test2.jsit('should take less than 500ms', function (done) {
this.timeout(500);
setTimeout(done, 300);});
<!DOCTYPE html><html lang="en">
<head>
<meta charset="utf-8" />
<title>Mocha Tests</title><meta name="viewport"
content="width=device-width, initial-scale=1.0" /><link rel="stylesheet" type="text/css"
href="https://unpkg.com/mocha/mocha.css"/>
</head>
<body>
<div id="mocha"></div>
<script src="https://unpkg.com/chai/chai.js"></script><script src="https://unpkg.com/mocha/mocha.js"></script>
<script class="mocha-init">
mocha.setup('bdd');
mocha.checkLeaks();
</script>
<script src="test2.js"></script>
<script class="mocha-exec">
mocha.run();
</script>
</body></html>
To watch for file changes and launch the tests automatically:
> npm test -- --watch
Press CTRL+C to terminate the watching process.