- Install mocha: npm i mocha --save-dev (-dev: this lib use only on dev mood)
- Create basic function for test (utils.js)
- Create test class for that (utils.test.js)
- Edit test line in package.json: "test": "mocha */.test.js"
- Run npm test
- To auto restart tests use: nodemon --exec "npm test"
- In commit 5: "test-watch":"nodemon --exec "npm test"" Run npm run test-watch
- Adding Assertion library:(mjackson/expect) to install this use: npm install [email protected] --save-dev
it('should add two numbers', ()=>{
var res = utils.add(55,5);
if(res !== 60){
throw new Error(`Expect 60 but got ${res}`);
}
});
it('sholud add one number',()=>{
var res = utils.squre(3);
expect(res).toBe(9).toBeA('number');
});
** when we working with object we need to use toEqual method .for objects toBe not working**
expect({name:"Shehan"}).toEqual({name:"Shehan"});
expect({name:"Shehan"}).toNotEqual({name:"Gamage"});
-
Asynchronous code testing with mocha. when we using async function we need to tell mocha that function is a async function. for that we can use done()
module.exports.asynAdd = (a, b, callback)=>{ setTimeout(()=>{ callback(a+b); },1000); };
it('should async add two numbers',(done)=>{ utils.asynAdd(3, 4, (sum)=>{ expect(sum).toBe(7).toBeA('number'); done(); }); });
-
Testing Express applications with supertest and mocha.
- install Express and create server.js.
- install (supertest) npm install supertest --save-dev
- Create server.test.js file.
-
Organizing test with describe(). using describe() we can organize out testing code
describe('sometext', ()=>{ //add test functions //add test functions //add test functions });
-
Test spies
-
Using rewire with spies npm install rewire --save-dev