Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we execute Unit Tests against DOM manipulation?

The introduction to QUnit over at netTuts.com spawns an interesting exchange (never resolved) over how to apply unit tests against actions that manipulate the DOM. The following quote (Alex York) gets to the crux:

What would be nice is that if you had a function like this:

function add(a, b) { var result = a + b; $(“input#ResultTestBox”).val(result);

In the above test, I would love to test two things: the addition of a and b, and the result correctly being put into a DOM element. I would love to test the second thing by providing some mock HTML. Possible?

But, like I said...unresolved. Resolvable?

like image 498
justSteve Avatar asked Oct 20 '10 01:10

justSteve


People also ask

How does Jest tests within a DOM environment?

How does Jest test within a DOM environment? Jest ships with jsdom, which simulates a DOM environment as if you were in a browser. This means that every DOM API that we call can be observed in the same way it would be observed in a browser.

How are unit tests executed?

Unit tests can be performed manually or automated. Those employing a manual method may have an instinctual document made detailing each step in the process; however, automated testing is the more common method to unit tests. Automated approaches commonly use a testing framework to develop test cases.


2 Answers

The latest version of QUnit supports a #qunit-fixture element that lets you add HTML to the QUnit web page.

E.g., in your HTML:

<ol id="qunit-tests"></ol>
<div id="qunit-fixture">test markup, will be hidden</div>

and in your JavaScript:

$('<input id="ResultTestBox" type="text"/>').appendTo('#qunit-fixture');
var result = add(a, b);

equals(result, $('input#ResultTestBox').val(), "testing result box value");
like image 139
Charles Anderson Avatar answered Oct 02 '22 01:10

Charles Anderson


Surely what you actually care about is that the val method gets called on the return value of $(“input#ResultTestBox”)—you don't need to test the functionality of the jQuery method itself. Why not inject a mock implementation of the jQuery object and test against that?

like image 22
Steve Greatrex Avatar answered Oct 02 '22 01:10

Steve Greatrex