This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Sinon Cheatsheet

Quick reference guide for Sinon.js, covering test spies, stubs, mocks, fake timers, fake servers, and sandbox lifecycle methods.

· Published

Creating Spies

fn = sinon.spy()
fn()
fn.calledOnce == true
fn.callCount == 1

Spying and Stubbing Methods

sinon.spy($, 'ajax')
$.ajax()
$.ajax.calledOnce == true
sinon.stub($, 'ajax', function () { /* ... */ }) // implementation function optional
$.ajax.calledWithMatch({ url: '/x' })
$.ajax.restore()

Spy and Stub Properties

spy
  .args        //=> [ [..], [..] ] one array per call
  .thisValues
  .returnValues
  .called      //=> true
  .notCalled
  .callCount
  .calledOnce
  .calledTwice
  .calledThrice
  .getCalls()   //=> Array of call objects
  .getCall(0)
  .firstCall

Anonymous Stubs

stub = sinon.stub().returns(42)
stub() == 42
stub
  .withArgs(42).returns(1)
  .withArgs(43).throws("TypeError")
stub
  .returns(1)
  .throws("TypeError")
  .returnsArg(0) // Return 1st argument
  .callsArg(0)

Fake Timers

sinon.useFakeTimers(+new Date(2011, 9, 1))

Fake Server

server = sinon.fakeServer.create()
$.get('/file.json', function (data) { /* ... */ })
server.requests[0].respond(
  200,
  { 'Content-Type': 'application/json' },
  JSON.stringify({ hello: 'world' })
)
server.restore()

Fake XHR

xhr = sinon.useFakeXMLHttpRequest()
xhr.restore()

Sandboxes

beforeEach(function() {
  global.sinon = require('sinon').sandbox.create()
})
afterEach(function() {
  global.sinon.restore()
})
```\n

Related topics