Stubbing middleware when testing an Express with Supertest


When testing a simple express app / api I like to use supertest.

This can feel like integration testing, and to an extent it is.
But we can stub things out with sinon, and tidy up our tests.

Let’s look at an example.

Suppose we have a simple API with the following router:

To run the app, we have a separate server.js:

This makes loading our app much easier in our supertest tests, as we’ll see later on.

Ok, nothing complex going on here –
We can see we have some authentication middleware on all of our routes:

This is some very basic authentication, for the purposes of our demo:

Ok, all is good, our app runs, and if we don’t supply an authentication token in the header, we’re returned a 401, otherwise, we’re presented with ‘Hello’

Our tests currently look like this:
(see the full test at this version here)

These all pass


The testing for with / without authentication header set stuff bothers me;
For a start, it’s a cross cutting concern – it shouldn’t be tested like this.
Plus – we’re integration testing our authentication middleware.
What happens if/when we make this more complex?

Much better would be to stub this out.

So, by changing our test slightly as follows:

We can create a stub of our ensureAuthenticated middleware.

Important here, is to note the removal of the “with authentication header set” tests… we don’t need them anymore! That’s taken care of by

Hope this helps!

I’ve added the full code on GitHub: GitHub

About the author

By Alex