Référence rapide

Aide-mémoire Sinon.js Spies & Stubs

Guide de référence rapide pour Sinon.js : test spies, stubs, mocks, faux minuteurs fake timers, serveurs simules et environnements sandbox.

· Publié le

Creation d'espions (Creating Spies)

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

Espionnage et substitution de methodes (Spying and Stubbing Methods)

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

Proprietes des Spies et Stubs (Spy and Stub Properties)

spy
  .args        //=> [ [..], [..] ] un tableau par appel
  .thisValues
  .returnValues
  .called      //=> true
  .notCalled
  .callCount
  .calledOnce
  .calledTwice
  .calledThrice
  .getCalls()   //=> Tableau d'objets d'appels
  .getCall(0)
  .firstCall

Bouchons anonymes (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) // Retourne le 1er argument
  .callsArg(0)

Minuteurs simules (Fake Timers)

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

Serveur simule (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()

XHR simule (Fake XHR)

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

Bacs a sable (Sandboxes)

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

References connexes

Sujets associés