【问题标题】:How JavaScript Unit testing worksJavaScript 单元测试的工作原理
【发布时间】:2018-07-24 14:53:24
【问题描述】:

考虑以下我的 javascript 函数的 sn-p -

firstJs.prototype.SetSum=function(a,b){
    var htmlToBind="<div>"+(a+b)+"</div>";
    $('#setSum').html(htmlToBind);
};

这里setSum 是 DOM 中的一个 elementID。我想了解这个函数将如何通过 Jasmine 或 Jest 完成的单元测试,因为当单元测试运行时它不会在 DOM 中找到“setSum”因此测试用例失败。我是测试用例的菜鸟

【问题讨论】:

    标签: javascript jquery unit-testing jasmine jestjs


    【解决方案1】:

    依赖注入之类的技术将在这里为您提供帮助。

    不要假设与$('#setSum')对应的元素对函数可用,而是将元素作为参数传入。

    例如,将您的函数转换为:

    function (a, b, element) {
        var htmlToBind = "<div>" + (a + b) + "</div>";
        element.innerHTML(htmlToBind);
    }
    

    现在,您的测试函数可以将任何 HTML 元素传递给第三个参数。

    【讨论】:

      【解决方案2】:

      您可以创建一个 id 为 setSum 的元素并附加到 DOM。使用 jasmine-jquery 这证明了一组可以用作匹配器的方法。

      希望这个sn-p有用

       describe('Your test description',function(){
          //rest of the code
          // appending an element to the DOM, the original function will append
          // the new div inside this element
         $('body').append('<div id = "setSum"></div>');
         it('Should test element is bind to DOM',function(){
             firstJS.SetSum(4,5);
             expect($('#setSum')).toContainHtml('<div>9</div>');
             // remove the element after test
      
           }}
      })
      

      如果您打算失败,请跳过$('body').append('&lt;div id = "setSum"&gt;&lt;/div&gt;');。测试将找不到 DOM,也无法对其使用html 方法

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-20
        • 2011-09-15
        • 2013-09-22
        • 2013-05-30
        • 1970-01-01
        相关资源
        最近更新 更多