Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing Javascript that involves the DOM

How do you go about unit testing javascript that uses and modifies the DOM?

I'll give an easy example. A form validator that checks for blank text fields, written in javascript and that uses JQuery.

      function Validator() {          this.isBlank = function(id) {             if ($(id).val() == '') {                 return true;             } else {                 return false;           }         };          this.validate = function(inputs) {             var errors = false;             for (var field in inputs) {                if (this.isBlank(inputs[field])) {                    errors = true;                    break;                }            }             return errors;        };     } 

Usage:

var validator = new Validator(); var fields = { field_1 : '#username', field_2 : '#email' };  if (!validator.validate(fields)) {     console.log('validation failed'); } else {     console.log('validation passed'); } 

What is the best practice for attempting to unit test something like this?

like image 530
BIOS Avatar asked Jun 01 '13 03:06

BIOS


People also ask

Can JavaScript be unit tested?

JavaScript Unit Testing is a method where JavaScript test code is written for a web page or web application module. It is then combined with HTML as an inline event handler and executed in the browser to test if all functionalities are working as desired. These unit tests are then organized in the test suite.

What is the best unit testing framework for JavaScript?

Jest was the most popular JavaScript unit testing framework in 2020. For web apps that are based on React, Jest is the preferred framework. Apart from React, Jest supports unit testing of Angular, VueJS, NodeJS, and others.

What are the challenges in JavaScript unit testing?

Challenges in JavaScript Unit Testing You can understand some system actions with other languages, but this is not the case with JavaScript. Some JavaScript are written for a web application may have multiple dependencies. JavaScript is good to use in combination with HTML and CSS rather than on the web.


1 Answers

Ideally you should split the code. The validation logic does not really require DOM access, so you would put that into its own function, and put the logic that processes the ID into a value that is then validated into another.

By doing this, you can more easily unit test the validation logic, and if necessary do a functional test on the whole thing using some of the tools suggested by Joseph the Dreamer.

like image 76
Jani Hartikainen Avatar answered Sep 21 '22 16:09

Jani Hartikainen