This article was peer reviewed by Mark Brown and MarcTowler. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!
One of the biggest stumbling blocks when writing unit tests is what to do when you have code that’s non-trivial.
All of these are hard to test because you can’t control them in code. If you’re using Ajax, you need a server to respond to the request, so as to make your tests pass. If you use setTimeout, your test will have to wait. With databases or networking, it’s the same thing — you need a database with the correct data, or a network server.
Real-life isn’t as easy as many testing tutorials make it look. But did you know there is a solution?
Put simply, Sinon allows you to replace the difficult parts of your tests with something that makes testing simple.
When testing a piece of code, you don’t want to have it affected by anything outside the test. If something external affects a test, the test becomes much more complex and could fail randomly.
And what if your code depends on time? Let’s say it waits one second before doing something. What now? You could use a setTimeout in your test to wait one second, but that makes the test slow. Imagine if the interval was longer, for example five minutes. I’m going to guess you probably don’t want to wait five minutes each time you run your tests.
Sinon helps eliminate complexity in tests by allowing you to easily create so called test-doubles.
Test-doubles are, like the name suggests, replacements for pieces of code used in your tests. Looking back at the Ajax example, instead of setting up a server, we would replace the Ajax call with a test-double. With the time example, we would use test-doubles to allow us to “travel forwards in time”.