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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With