gpt4 book ai didi

javascript - 尝试用 Jasmine 测试 jQuery

转载 作者:行者123 更新时间:2023-12-02 23:20:55 25 4
gpt4 key购买 nike

我用 JavaScript 创建了一个非常简单的账单分割应用程序,并使用 Jasmine 进行测试。

我正在尝试测试这个计算函数:


function Bill_Splitter(){
this.amount = 0;
this.cost = 0;
this.tip = 0;
this.diners = 0;
};

Bill_Splitter.prototype.calculate = function(){

this.cost = parseInt(document.getElementById("cost").value);
this.tip = parseInt(document.getElementById("tip").value);
this.diners = parseInt(document.getElementById("diners").value);

var amount = (cost + tip) / diners

return this.amount += amount
document.getElementById("amount").innerHTML = amount

}

但是,我不知道如何测试用户输入的 HTML 表单中的数值(成本、小费和值(value))。

到目前为止我的 Jasmine 测试是:


describe('calculate', function() {
const form = document.createElement('form');
form.innerHTML= `<input type="text" id="cost" value=2 />
<input type="text" id="tip" value=2 />
<input type="text" id="diners" value =2 />
<span id="amount"></span>
`;
document.body.appendChild(form)
splitter.calculate()
expect(splitter.amount).toEqual(30)
});
});

有人可以帮忙吗?谢谢! :)

最佳答案

您可以像在函数构造函数中使用 this.amount 一样创建属性

 function Bill_Splitter(){
this.amount = 0;
this.cost = 0;
this.diners = 0;
this.tip = 0;
};
 this.cost = parseInt(document.getElementById("cost").value);
this.tip = parseInt(document.getElementById("tip").value);
this.diners = parseInt(document.getElementById("diners").value);

describe('calculate', function() {
it('calculates the amount due', function(){
splitter.calculate()
expect(splitter.amount).toEqual(30)
expect(splitter.tip).toEqual(###)
});
});

如果您的测试找不到这些 html 元素,您可以将它们添加到您的测试中:

it('calculate', function(){
const form = document.createElement('form');
form.innerHTML= `<input type="text" id="cost" value="2" />
<input type="text" id="tip" value="2" />
<input type="text" id="dinners" value ="2" />
<span id="amount"></span>
`;
document.body.appendChild(form)

splitter.calculate()

expect(splitter.amount).toEqual(30)
expect(splitter.tip).toEqual(###)
})


最终代码:

function Bill_Splitter(){
this.amount = 0;
this.cost = 0;
this.tip = 0;
this.diners = 0;
};

Bill_Splitter.prototype.calculate = function(){
this.cost = parseInt(document.getElementById("cost").value);
this.tip = parseInt(document.getElementById("tip").value);
this.diners = parseInt(document.getElementById("diners").value);

this.amount += (this.cost + this.tip) / this.diners;

document.getElementById("amount").innerHTML = this.amount

}

关于javascript - 尝试用 Jasmine 测试 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56957322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com