简体   繁体   English

如何使用Jasmine / Karma测试对DOM元素的修改?

[英]How to test modification to DOM elements with Jasmine/Karma?

I created simple function in Javascript that when instantiated as an object takes a DOM element as a parameter and then via its various methods can modify this element eg show, hide, apply classes etc. 我用Javascript创建了一个简单的函数,当实例化为一个对象时,将DOM元素作为参数,然后通过其各种方法可以修改此元素,例如show,hide,apply classes等。

I want to write unit tests to test its functionality but am not sure whats the best way to do this. 我想编写单元测试来测试其功能,但不确定执行此操作的最佳方法是什么。

Having example below: 以下是示例:

var Ns = {};

Ns.Dropdown = function(options) {

    this._$el = $(options.el);
    this._$ul = this._$el.find("ul");
}

Ns.Dropdown.prototype.open = function() {

    this._$ul.addClass("open");
}

How would I test that .open() does what its suppose to do. 我将如何测试.open()是否应做的事情。 It suppose to make ul visible via appending class open and what would be the best way to test it? 它假设通过追加类open使ul可见,并且测试它的最佳方法是什么? I created this short test using Jasmine (with Karma) and when it runs it fails: 我使用Jasmine(与Karma)创建了此简短测试,并且运行时失败:

describe("DropDown Selector", function() {

    var dd;

    beforeEach(function() {

        var element = document.createElement("div");

        element.innerHTML = '<div id="someId" class="">
            <span class="trigger"></span>
<ul><li data-value="0"><span>Hourly</span></li>
<li data-value="1"><span>Daily</span></li>              
<li data-value="2" class="selected"><span>Weekly</span></li>                                
</ul></div>';

        dd = new Ns.Dropdown({
            el: $("#someId")[0]
        });

    });

    it("Should open popup", function() {
        dd.open();
        expect($("#someId ul").hasClass("open")).toBeTruthy();
    });
});

I assume that when it runs the element is not appended to DOM just yet and $("#someId ul").hasClass("open") is false , even though that dd._$ul has class open on it already. 我假设当它运行时,该元素还没有追加到DOM上,并且$("#someId ul").hasClass("open")false ,即使该dd._$ul已经打开了类。

How would I test for this sort of thing where functions making modifications to DOM? 在功能对DOM进行修改的情况下,我将如何测试这种情况?

(For reference) : It might help to actually attach the element to the DOM. (仅供参考):将元素实际附加到DOM可能会有所帮助。

This is the technique used in the jasmine-jquery lib, with wich you can write : 这是jasmine-jquery lib中使用的技术,您可以编写以下代码:

element = document.createElement("div");
...
jasmine.getFixtures().set(element);
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM