- Doing stuff in the terminal is not scary at all
- npm is not only for getting packages
- Package.json is a mighty tool
- Git is not that hard, but I need to refresh my knowledge
- Callback function is cool stuff, and I even know how to write them
- mocha is cool both as framework and test runner
- Should is a nice way to do asserts
- monk is an easy way to access mongo
- Express is best without generators
- supertest is a nice way to test an api - this post
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.