Testing in the Console!

The Console’s assert method lets you run tests in the browser with a very simple syntax.

1 console.assert(true === false, "True is not false!");
2 // Assertion failed: True is not false!

The assert method accepts two arguments: an expression to be evaluated and an object to be logged when the expression is false.

A Somewhat Practical Example

1 var anchors = document.getElementsByTagName("a");
2 for (var i = anchors.length - 1; i >= 0; i--) {
3   console.assert(anchors[i].title, anchors[i], "is missing a title!");
4 };
5 // Assertion failed: <a href=​"/​">​Home​</a>​ is missing a title!

In this example, we’re looping over all anchors on a page, checking for titles, and logging the assertion failure along with an expandable DOM object for each each failure.