简体   繁体   中英

Testing Number.prototype with Mocha

Let's say I have a function on Javascript's Number prototype as follows:

controllers/index.js

Number.prototype.adder = function(num) {
    return this+num;
}
module.exports = Number;

However, the following Mocha/Chai tests are failing

var expect= require("chai").expect;
var CustomAdder= require("../controller/index.js");
describe("adder", function () {
    var one= 4;
    var two= 5;

    it("should add 4 and 5 to 9", function(done){
        expect(one.CustomAdder(5)).to.equal(9);
        done();
    });


    it("should not add 5 and 6 to 11", function(done){
        expect(two.CustomAdder(6)).to.not.equal(12);
        done();
    });

});

Error: TypeError: undefined is not a function

I am pretty sure that the problem is caused by the module.exports = Number part. So basically my question is- how do I export a function in Number.prototype to make it testable as above.

Your function is called adder, so you should do

expect(one.adder(5)).to.equal(9);

Instead of

expect(one.CustomAdder(5)).to.equal(9);    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM