Marcus Node Bits - supertest is a nice way to test an api'

· February 7, 2014

I’m writing down some of the things I’ve picked up when I started to learn about NodeExpress and Mongo. Here are all the post in the series:

This post is about a testing framework for HTTP: supertest.

Really, I shouldn’t need to write anything more after stating the name of the module. That’s SUPER testing people. That’s all we really need…

It’s called supertest since it depends on a module called super-agent, an HTTP client. This is important to know since the supertest library is actually just extending the super-agent library. Many of the functions you use when writing tests with supertest is defined in super-agent. So if you need to look something up you might have to peek that the documentation of super-agent.

The supertest  library is very handy when it comes to test API and web applications and have a nice fluent interface that I immediately fell in love with. You install it, of course, with

npm install supertest

As always the best way to show you this is with an example. Let’s write a little test for a simple GET

See, that was very simple. Note the fluent interface and how you first compose your request (the .get() and .set() functions) and then we can do the expects, all in one statement. It’s pretty nice, I think!

The app object needs to be exported from the app-file so that the test can get hold of it. This is done with the

module.exports.getApp = app;

statement so it’s not too bad. In return you get a very simple way of testing the express application that don’t even have to be up and running, it’s all in-process of the test. At least that’s my current understanding of it.

Now let’s do a post as well and see how to send data to the server:

Here you can see me use the URL instead of the app-object. I (think that I) then have to make sure that the application is up and running so it’s a bit more complex with more moving parts.

If you need to test things that are under authentication there’s a great post about that over here. 

There’s not really much more to say about this framework. It’s one of those - “it just works”-frameworks which is awesome. In doubt checkout the documentation for supertest and super-agent.

Twitter, Facebook