如何使用 mocha & chai 测试 js 工厂函数

How to test js factory function using mocha & chai

我正在尝试测试我的 DOM 项目,因此它应该确保成本为 2.75,短信为 0.75。它 returns 一个断言错误,表示预期 2.75 等于未定义。我需要帮助 访问呼叫和短信的正确值。 这是我的工厂函数

    var callCost = 0;
    var smsCost = 0;
    var totalCost = 0;

    const warning = 30;
    const critical = 50;

    function getCall() {
        return callCost;
    }

    function getSms() {
        return smsCost;
    }

    function getTotal() {
        totalCost = callCost + smsCost;
        return totalCost;
    }

    function radioButtons(selectedBill) {
        if (selectedBill === "call") {
            callCost += 2.75;
        } else if (selectedBill === "sms") {
            smsCost += 0.75;
        }
    }

    function totalClassName() {
        if (getTotal() >= warning && getTotal() < critical) {
            return "warning";
        } else if (getTotal() >= critical) {
            return "critical";
        }
    }

    return {
        getCall,
        getSms,
        getTotal,
        radioButtons,
        totalClassName
    }
}


describe('The radio-bill function', function(){
    it('Should be able to add call at 2.75', function(){
        var itemType = RadioBill();
        itemType.radioButtons("call");
        assert.equal(2.75, itemType.radioButtons("call"))
    })
})

您只需更改 assert 行即可让您的测试工作。

var itemType = RadioBill();
itemType.radioButtons("call");
assert.equal(itemType.getCall(), 2.75);

在这里,首先要注意的是调用 assert 时参数的顺序很重要。第一个参数是 actual 值,第二个参数是 expected 值。通常情况下,但并非总是如此,实际值将是操作的结果,而预期值将是常量。

第二点是,在您的代码中,函数 radioButtons 没有 return 值,它只是更改内部状态变量的值。但是已经有函数 getCall 来获取该值,这就是 assert 行正在检查的内容。