简体   繁体   中英

How to test js factory function using mocha & chai

I am trying to test my DOM project, so it should make sure that the cost is 2.75 and sms is 0.75. It returns an assertion error that says expected 2.75 to equal undefined. I need help accessing the correct values of call and sms. Here's my factory function

    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"))
    })
})

You only need to change your assert line to get your test working.

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

Here, the first thing to note is that the order of the arguments in a call to assert does matter. The first argument is the actual value, the second one is the expected value. Typically, but not always the actual value will be the result of an operation, and the expected value will be constant.

The second point is that in your code the function radioButtons does not return a value, it just changes the value of an internal state variable. But there is already the function getCall to get that value, and that is what the assert line is checking.

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