【问题标题】:NodeJs unit test actual results not correctNodeJs单元测试实际结果不正确
【发布时间】:2017-03-05 22:55:00
【问题描述】:

我正在使用简单的方法和 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)

我认为这很奇怪,因为带有“notgoodcode”的 15 岁会过去,但 65 岁以上的年龄永远不会过去,并且会重定向到第一个 if 语句而不是第二个。

提前谢谢你。

【问题讨论】:

    标签: node.js unit-testing npm


    【解决方案1】:

    这与运算符优先级有关。 &amp;&amp;|| 之前执行。要获得预期的结果,您需要添加括号。

    if ((age >= 65 || age <= 15) && code == "abcd" || code == "efgh") {
    
    }  else if ((age >= 65 || age <= 15)  && code == "notgoodcode") {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多