Chapter 16: Testing

So far, every time you have written a Node program, you have verified it worked as expected by running it and observing that its behavior matched your expectations. This method of testing is often insufficient to ensure that programs work correctly and don’t introduce new bugs as time goes by.

Automated testing is the process by which a series of programs are executed to verify that the intended function is in place. The first approach to automated testing in this chapter consists of creating one small node program per test and leveraging the native assert module.

Next, you optimize the process of writing assertions by leveraging a project called expect.js. You then explore how to organize testing by leveraging Mocha, a test framework.

Finally, for codebases that are meant to be run in browser and server environments, you will see how to take your existing tests and also run them on the browser.

Simple testing

To get started, you’ll need to identify a test subject. In other words, you’ll decide what script or functionality you want to write tests for.

The test subject

The test subject for this chapter is the application you wrote in Chapter 9 for searching tweets.

Here, you write a program which asserts that upon submitting a search keyword, a list of tweets is returned after the program looks for some indicative pieces of HTML. In this case, a list of tweets is composed of one or more <li> elements. Asserting the presence of the search keyword and the ...

Get Smashing Node.js: JavaScript Everywhere, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.