Mock-Testing a Node Server with Supertest

In the previous section, we tested each of our Backbone entities against a mock server, using Sinon to fake responses to each collection’s HTTP requests. Now it’s time to create the mirror image of those tests, testing that our server provides the correct response to a set of fake requests.

Before we start writing tests, though, we should refactor our server to make it test-friendly. As we wrote it originally, it would define an Express instance (called app) and then immediately start listening on a port. For testing, we don’t want to actually open a TCP port. It’s much easier to simulate our requests. So let’s separate the code that defines app from the code that tells app to start listening:

Get CoffeeScript, 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.