In my recent Javascript project, I developed a simple function that behaves as an object when instantiated. This function takes a DOM element as a parameter and can modify the element using various methods like showing, hiding, or applying classes.
Now, I am faced with the challenge of writing unit tests to ensure the functionality of this function. One specific method, .open()
, is intended to make a ul
element visible by adding the class open
. How can I effectively test this behavior?
For instance, consider the following code snippet:
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");
}
I attempted to create a test using Jasmine (with Karma), but it failed to pass:
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();
});
});
Upon investigation, I realized that the element may not be appended to the DOM at the time the test runs, causing the assertion $("#someId ul").hasClass("open")
to return false. This discrepancy occurred despite the fact that dd._$ul
already had the "open" class applied to it.
So, how can I proceed with testing functions that manipulate the DOM in a similar fashion?