我用简单的方法和if语句进行单元测试但是我的预期结果必须是8但是测试给出的错误实际上是7
这是我的单元测试:
describe("Discount code 10% + 20% age", function() {
it("If code is abcd or efgh give 10% discount and if age is lower than 15 or higher than 65 plus 20% discount ", function() {
// Hier worden variabelen gekopeld aan de returns van de functies
var testCaseDiscount1 = converter.calculateTotalPrice(66, "abcd");
var testCaseDiscount2 = converter.calculateTotalPrice(15, "efgh");
var testCaseDiscount3 = converter.calculateTotalPrice(64, "fffhfh");
var testCaseDiscount4 = converter.calculateTotalPrice(20, "fdhdfhfd");
var testCaseDiscount5 = converter.calculateTotalPrice(15, "notgoodcode");
var testCaseDiscount6 = converter.calculateTotalPrice(67, "notgoodcode");
// Hier worden de antwoorden vergeleken.
expect(testCaseDiscount1).to.equal(7);
expect(testCaseDiscount2).to.equal(7);
expect(testCaseDiscount3).to.equal(10);
expect(testCaseDiscount4).to.equal(10);
expect(testCaseDiscount5).to.equal(8);
expect(testCaseDiscount6).to.equal(8);
});
});
我的if语句:
exports.calculateTotalPrice = function(age, code) {
var price = 10;
if (age >= 65 || age <= 15 && code == "abcd" || code == "efgh") {
var result = (price / 100 * 30 );
var price = (price - result);
return price;
} else if (age >= 65 || age <= 15 && code == "notgoodcode") {
var result = (price / 100 * 20 );
var price = (price - result);
return price;
} else {
return price;
}
}
我的结果将是:
AssertionError: expected 7 to equal 8
+ expected - actual
-7
+8
at Context.<anonymous> (test\TicketTest.js:50:38)
我认为这很奇怪,因为15岁的时候,&#34; notgoodcode&#34;将通过,但65岁以上的年龄将永远不会通过,并将重定向到第一个if语句而不是第二个。
提前谢谢。
答案 0 :(得分:1)
这与运营商优先级有关。 &&
之前执行||
。要获得预期结果,您需要添加括号。
if ((age >= 65 || age <= 15) && code == "abcd" || code == "efgh") {
} else if ((age >= 65 || age <= 15) && code == "notgoodcode") {