How to Test an API with Node.js
By: Jed Wood
Testing an API with Node.js is dead simple. You can quickly write tests for any API, regardless of its language.
Hackers Donít Test
I donít like writing tests. Just ask any of my coding teammates. I spent too many years slapping together quick protoypes that were just for proof of concept and didnít need to be maintained. I think of testing like financial accounting; I know itís vital to keep operations running smoothly, but I much prefer if somebody else handles it.
Iím getting better though, and itís paying off. Youíve probably already read about the reasons you should write tests. If youíre still not convinced, consider this: itís quickly becoming table stakes for most modern web development projects, much like knowing how to use Github. If you want to contribute to open source projects, or make it past your first interview, youíve gotta write tests.
Unit, Integration, Functional, and Acceptance
Iím going to skip the philosophy and finer points. Read this answer for a great explanation of the different types of tests. On the most granular level we have unit tests. On the other end of the spectrum were have browser-testing tools like PhantomJS or SaaS options like BrowserStack and Browserling. Weíre going to be closer to that high level testing, but since this is purely an API, we donít need a browser.
Our Example API
Letís take a look at our example API, which is a protected pretend blog. In order to show off some of the testing options, this API:
* requires Basic Auth
* requires an API key be passed in as a custom header
* always returns JSON
* sends proper status codes with errors
Mocha, Chai, and SuperTest
If youíve spent 30 minutes tinkering with Node.js, thereís a really good chance youíve seen the work of TJ Holowaychuck and his army of ferrets. His Mocha testing framework is popular and weíll be using it as a base. Fewer people have seen his SuperTest library, which adds some really nice shortcuts specifically for testing HTTP calls. Finally, weíre including Chai just to round out the syntax goodness.
... to read more articles, visit http://sqa.fyicenter.com/art/