Snabbreferens

Sinon.js Test-spies & Stubs Lathund

Snabbreferens foer Sinon.js: test-spies, stubs, mocks, falska timers, simulerade servrar och sandlador sandboxes.

· Publicerad

Skapa spies (Creating Spies)

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

Oevervaka och ersatta metoder (Spying and Stubbing Methods)

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

Egenskaper foer spies och stubs (Spy and Stub Properties)

spy
  .args        //=> [ [..], [..] ] en array per anrop
  .thisValues
  .returnValues
  .called      //=> true
  .notCalled
  .callCount
  .calledOnce
  .calledTwice
  .calledThrice
  .getCalls()   //=> Array av anropsobjekt
  .getCall(0)
  .firstCall

Anonyma 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) // Returnerar 1:a argumentet
  .callsArg(0)

Simulerade timers (Fake Timers)

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

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

Simulerad XHR (Fake XHR)

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

Sandlador (Sandboxes)

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

Relaterade referenser

Relaterade ämnen