Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Unit Testing - DOM Manipulation

I'm quite new to Javacript Unit testing. One thing keep bothering me. When testing javascript, we often need to do the DOM manipulation. It looks like I am unit testing a method/function in a Controller/Component, but I still need to depend on the HTML elements in my templates. Once the id(or attributes used to be selectors in my test cases) is changed, my test cases also need to be CHANGED! Wouldn't this violate the purpose of unit testing?

like image 468
Jia Avatar asked Sep 17 '13 14:09

Jia


People also ask

Can JavaScript be used to manipulate the DOM?

The DOM stands for Document Object Model. It can simply be understood as a tree of nodes created by the browser. Each of these nodes has its own properties and methods which can be manipulated using JavaScript. The ability to manipulate the DOM is one of the most unique and useful abilities of JavaScript.

How important is DOM manipulation in JavaScript?

It allows a language (JavaScript) to manipulate, structure, and style your website. After the browser reads your HTML document, it creates a representational tree called the Document Object Model and defines how that tree can be accessed.


1 Answers

One of the toughest parts of javascript unit testing is not the testing, it's learning how to architect your code so that it is testable.

You need to structure your code with a clear separation of testable logic and DOM manipulation.

My rule of thumb is this:

If you are testing anything that is dependent on the DOM structure, then you are doing it wrong.

In summary:Try to test data manipulations and logical operations only.

like image 90
BentOnCoding Avatar answered Sep 28 '22 12:09

BentOnCoding