使用 Mocha 测试 Number.prototype

Testing Number.prototype with Mocha

假设我在 Javascript 的 Number 原型上有一个函数,如下所示:

controllers/index.js

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

但是,以下 Mocha/Chai 测试失败

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();
    });

});

错误:类型错误:undefined 不是函数

我很确定问题是由 module.exports = Number 部分引起的。 所以基本上我的问题是 - 如何在 Number.prototype 中导出函数以使其可测试如上。

你的函数叫做加法器,所以你应该这样做

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

而不是

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