Diff.Thinkr
Diff.Thinkr

Reputation: 855

Javascript Unit test DOM elements

I just started building unit tests (using QUnit) for my javascript and I have a function which takes a div and manipulates its children.

How can I create a test for this?

I was thinking of creating a document fragment with the expected DOM tree in each case and test against it. But since the parents etc are different, wouldn't a recursive check fail? How else can I do this test?

Upvotes: 1

Views: 1039

Answers (2)

Diff.Thinkr
Diff.Thinkr

Reputation: 855

I found a node.isEqualNode() function that seems to do the required work. It doesn't seem to compare attributes. I want classNames,ids and data-* attributes also to be compared.

Upvotes: 0

Raynos
Raynos

Reputation: 169401

Have a DOM reset function that you can call after every test to get back into a neutral state.

Run your function that manipulates the DOM.

Then manually check the DOM is in the correct state by going through it and just asserting everything is where it should be.

Rather recursively comparing it with a DOMFragment loop through the DOM and check that your function has created the new elements, changed classes, changed text, changed attributes, etc.

After you've written a few tests, wrap things in functions and DRY your code out.

Writing code like this means you will probably duplicate a lot of code in your unit tests where your checking very similar things in the DOM. To make it nicer to re-use these take common pieces of code and place them in functions.

Upvotes: 1

Related Questions