Snelle referentie

Sinon.js Spies & Stubs Spiekbrief

Korte referentiegids voor Sinon.js: test-spies, stubs, mocks, fake timers, fake servers en sandbox-levenscyclusmethoden.

· Gepubliceerd

Spies aanmaken (Creating Spies)

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

Methoden observeren en vervangen (Spying and Stubbing Methods)

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

Spy- en Stub-eigenschappen (Spy and Stub Properties)

spy
  .args        //=> [ [..], [..] ] een array per aanroep
  .thisValues
  .returnValues
  .called      //=> true
  .notCalled
  .callCount
  .calledOnce
  .calledTwice
  .calledThrice
  .getCalls()   //=> Array van aanroep-objecten
  .getCall(0)
  .firstCall

Anonieme Stubs (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) // Retourneert 1e argument
  .callsArg(0)

Gesimuleerde timers (Fake Timers)

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

Gesimuleerde server (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()

Gesimuleerde XHR (Fake XHR)

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

Zandbakken (Sandboxes)

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

Gerelateerde referenties

Verwante onderwerpen