Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 56 ยท Migration and Performance

Testing and Debugging jQuery Code

Structure jQuery code into testable modules, check selectors, build a tiny assertion helper, use fixtures for DOM tests and debug with the console and devtools.

jQuery code has a reputation for being hard to test, and the reputation is earned: a 300-line $(document).ready() block that reads the page, changes it, and talks to a server all in one function has nothing you can call from outside. The library is not the problem. The structure is. When logic lives in small functions that take values and return values, and only a thin layer touches the DOM, testing becomes easy and debugging becomes quick.

In this lesson you will separate logic from DOM code, write a tiny assertion helper (no framework needed), test DOM behavior against a fixture, learn the console and devtools techniques that find most bugs in minutes, and see what a real test runner like QUnit looks like. The previous lesson on best practices pairs well with this one.

Three layers

Logic Pure functions: values in, values out.
DOM glue Small functions that read or write elements.
Wiring Ready handler that connects the two.

Test the first layer a lot, the second a little, the third by hand.

1 / 2

Structure code so it can be tested

Compare two ways to write a price total. In the first, the calculation is welded to the page:

JavaScript
$("#total").on("click", function () {
  var sum = 0;
  $(".price").each(function () { sum += parseFloat($(this).text()); });
  $("#result").text("$" + sum.toFixed(2));
});

To test it you would need a page, buttons and click simulation. Now split it:

JavaScript
function sumPrices(values) {
  return values.reduce(function (sum, value) { return sum + value; }, 0);
}

function formatMoney(amount) {
  return "$" + amount.toFixed(2);
}

$("#total").on("click", function () {
  var values = $(".price").map(function () { return parseFloat($(this).text()); }).get();
  $("#result").text(formatMoney(sumPrices(values)));
});

sumPrices() and formatMoney() can be called with plain arrays and numbers, in any order, with edge cases like an empty list. Only the last block needs a browser. Keep your logic functions in an object or a function scope (the module pattern) so they do not become globals:

JavaScript
var Cart = (function () {
  function sum(values) { /* ... */ }
  function format(amount) { /* ... */ }
  return { sum: sum, format: format };
})();

A tiny assertion helper

You do not need a framework to start testing. A test is a function that checks that something is true, and a runner collects the results. Here is about twenty lines that do it, with the report printed on the page. Read the code, then click Run tests.

A mini test runner for logic functions

The last test fails on purpose so you can see a failure report. The number 1.005 cannot be stored exactly in binary floating point; it is slightly below 1.005, so toFixed(2) gives "1.00", not "1.01". A good failure message, like this one, says what was expected and what arrived.

Testing DOM code with fixtures

Code that touches elements needs elements. A fixture is a small piece of HTML created fresh before each test and removed afterward, so tests cannot affect each other. Create it inside a hidden container on the test page, run the code under test against it, assert on the result, and clean up.

jQuery helps here: .trigger("click") runs the handlers just as a user click would, so you can test an interaction without a mouse. Write DOM code as a function that receives the root element (function initCounter($root)) instead of reaching for $("#counter"), so each test can hand it its own fixture.

Testing a widget against a fixture

One subtlety: jQuery's delegated click handlers skip disabled form controls, just as the browser does for real clicks. That is why the second test can rely on .prop("disabled") to prove the limit was reached.

Console and devtools techniques

Most bugs fall to a small kit of tools. Learn them well and you will rarely need anything fancier.

  • console.log($el.length, $el) answers "did the selector match?" and lets you expand the collection in the console to see which elements it holds. console.table() is excellent for arrays of objects, and console.dir($el[0]) shows an element's properties instead of its markup.
  • debugger; pauses execution at that line when devtools is open. You can inspect this, the event object and every variable in scope, then step line by line.
  • Breakpoints set in the Sources panel do the same without editing code. Event listener breakpoints pause on the next click or keypress, and DOM breakpoints (right-click an element, Break on...) pause when a script changes its subtree or attributes.
  • $0 in the console is the element currently selected in the Elements panel. Type $($0).data() to see everything jQuery stored on it, or $._data($0, "events") to list its handlers (that last helper is internal and may change; use it only while debugging).
  • monitorEvents($0, "click") logs every click on the selected element, a quick way to prove an event is being fired at all.
  • The Network panel shows AJAX requests, their status codes and response bodies, which settles the question "did the server send what I think it did?".
  • console.time("label") and console.timeEnd("label") measure how long a block takes.

A tiny plugin can make chains debuggable. Because it returns this, you can drop it anywhere in a chain and remove it afterward:

JavaScript
$.fn.peek = function (label) {
  console.log(label || "peek", this.length, this.get());
  return this;
};

$(".row").filter(".active").peek("active rows").addClass("seen");

What a real test runner looks like

When a project grows past a few dozen tests, a framework adds grouping, async support, reporting and a way to run tests from the command line. QUnit was created by the jQuery team and is still used by the jQuery project itself; Jest and Vitest are popular choices that run in Node with a simulated DOM (jsdom). The QUnit shape is familiar after our mini runner. This snippet is read-only because the sandbox cannot load a test page.

JavaScript
QUnit.module("Counter", {
  beforeEach: function () {
    this.$fx = $("#qunit-fixture").html('<div class="counter"><span class="value">0</span><button class="inc">+</button></div>');
  }
});

QUnit.test("increments on click", function (assert) {
  initCounter(this.$fx.find(".counter"), 3);
  this.$fx.find(".inc").trigger("click");
  assert.strictEqual(this.$fx.find(".value").text(), "1", "value shows 1");
});

QUnit resets #qunit-fixture after every test for you, the same job withFixture() did above. Whichever runner you choose, the principles are the same: keep logic separate from the DOM, give every test its own fixture, assert on visible results, and make failure messages tell you what went wrong.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why split a click handler into a pure calculation function plus a small DOM function?

    Logic that takes values and returns values can be called from a test with any input. Only the thin DOM layer needs a page.
  2. 2. What is a fixture in a DOM test?

    Fixtures give every test an isolated, known starting point so tests do not affect each other.
  3. 3. You select $(".row") and nothing happens. What should you check first?

    jQuery ignores calls on empty collections without any error, so a length of 0 is the most common cause.
  4. 4. What does the debugger statement do?

    At a pause you can inspect variables, this and the event, then step through the code.
  5. 5. Why does a plugin like $.fn.peek return this?

    Returning this keeps the jQuery object flowing to the next method, so a debugging step can be inserted and removed freely.

Summary

  • Separate pure logic from DOM glue and wiring; test the logic heavily and keep the DOM layer thin.
  • A test is a function that throws when an assertion fails; a few lines of helper code make a working runner.
  • Give each DOM test a fixture, trigger events with .trigger() and clean up with .remove().
  • Log .length first, then use debugger, event listener breakpoints, $0, monitorEvents() and the Network panel.
  • A small chainable helper like $.fn.peek makes debugging chains easy.
  • QUnit, Jest and Vitest offer the same ideas with grouping, async support and reports.

Time to apply everything in a complete app: Project: To-Do List.