node.js - How to test javascript function independently with mocha chai and sinon? -
i new unit testing , have been reading few tutorials practice javascript. use silly example explain problem.
let's john needs go school , before knowing if he's ready go has check if has bag , headphones. called following function:
john.isreadytogo;
the implementation of isreadttogo() function character object follows:
characher.isreadytogo = function() { return this.hasbag() && this.hasheadphones(); } characher.hasbag = function() { // return true or false } characher.hasheadphones = function() { //return true or false }
now, let's want test function. in unit testing recommended test functions without them being affected other functions. means in case have test 3 functions character.isreadytogo() function need have mock values this.hasbag() , this.hasheadphones(). right?
if so, give me hint on how can mock these 2 values?
here's example:
let character = {}; character.isreadytogo = function() { return this.hasbag() && this.hasheadphones(); } character.hasbag = function() { // return true or false } character.hasheadphones = function() { //return true or false } const sinon = require('sinon'); const expect = require('chai').expect; describe('is character ready?', () => { beforeeach(() => { sinon.stub(character, 'hasbag'); sinon.stub(character, 'hasheadphones'); }); aftereach(() => { character.hasbag.restore(); character.hasheadphones.restore(); }); it("not if don't have bag or headphones", () => { character.hasbag.returns(false); character.hasheadphones.returns(false); expect(character.isreadytogo()).to.be.false; }); it("not if have headphones no bag", () => { character.hasbag.returns(false); character.hasheadphones.returns(true); expect(character.isreadytogo()).to.be.false; }); it("not if have bag no headphones", () => { character.hasbag.returns(true); character.hasheadphones.returns(false); expect(character.isreadytogo()).to.be.false; }); it("yes, if have bag , headphones", () => { character.hasbag.returns(true); character.hasheadphones.returns(true); expect(character.isreadytogo()).to.be.true; }); });
for each test, stubs character.hasbag
, character.hadheadphones
(this done in beforeeach
). replaces original new function (the stub) can control.
depending on test, stub "told" return each function (using .returns()
), isreadytogo
called, , result checked against expectation.
after each test, stub restored (meaning original function restored).
Comments
Post a Comment