Unit Testing with Sinon.js

“Close-up of lines of code on a computer screen” by Ilya Pavlov on Unsplash

When writing unit tests for javascript code, there may be a time when you need to stub part of your code in order to isolate and test a particular functionality of your code. This is where Sinon.js is a popular tool to help developers test their code.

Stubs and Spies

A sinon spy allows the code to be called without breaking the rest of the application, and it can be tested to check whether it was called or not and how many times it was used.

A stub is essentially same as a spy except that it has a predetermined behaviour such as what to return when an ajax call is stubbed.

Fake Timer

“Fake timers is a synchronous implementation of setTimeout and friends that Sinon.JS can overwrite the global functions with to allow you to more easily test code using them.”

This is particularly useful when you are trying to test time specific code. For example when a given dataset is dependent on system time and don’t want to keep changing the test time.

For further information on any of these functions, there are detailed documentation on http://sinonjs.org

Joon
Junior Software Developer


Originally published at techbrunch.gousto.co.uk on January 18, 2017.

Like what you read? Give GoustoTech a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.