Unit Testing with Sinon.js

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
it('should use stub and spies', function() {
const result = 'result'
const spy = sinon.spy()
const stub = sinon.stub().returns(new Promise(resolve => { resolve(result) }))
const component = require('inject?actions!component')({
actions: { stub },
}).default

const stubResult = component()

expect(spy).to.have.been.called
expect(stubResult).to.equal('result')
})

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.

1
2
3
4
5
6
7
8
9
it('should useFakeTimers', function() {
const clock = sinon.useFakeTimers(new Date(2000, 01, 01).getTime())

const testTime = component()

expect(testTime).to.equal('2000-01-01')

clock.restore()
})

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

Joon
Junior Software Developer