尝试使用Jasmine测试jQuery

时间:2019-07-09 16:53:40

标签: javascript jquery jasmine

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

我正在尝试测试此calculate函数:


    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表单中的值。

到目前为止,我的茉莉花测试是:


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

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

1 个答案:

答案 0 :(得分:1)

您可以像在函数构造函数中使用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 

}