Kurzreferenz

Sinon.js Test-Spies & Stubs Spickzettel

Umfassende Kurzreferenz fuer Sinon.js: Test-Spies, Stubs, Mocks, Fake-Timer, Fake-Server und Sandbox-Lebenszyklusmethoden.

· Veröffentlicht

Erstellen von Spies (Creating Spies)

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

Methoden beobachten und ersetzen (Spying and Stubbing Methods)

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

Spy- und Stub-Eigenschaften (Spy and Stub Properties)

spy
  .args        //=> [ [..], [..] ] ein Array pro Aufruf
  .thisValues
  .returnValues
  .called      //=> true
  .notCalled
  .callCount
  .calledOnce
  .calledTwice
  .calledThrice
  .getCalls()   //=> Array von Aufruf-Objekten
  .getCall(0)
  .firstCall

Anonyme 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) // Gibt das 1. Argument zurueck
  .callsArg(0)

Gefaelschte Timer (Fake Timers)

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

Gefaelschter 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()

Gefaelschtes XHR (Fake XHR)

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

Sandboxes

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

Verwandte Referenzen

Verwandte Themen