Referencia rápida

Hoja de referencia de Sinon.js Spies y Stubs

Guia rapida de referencia para Sinon.js: test spies, stubs, mocks, temporizadores falsos (fake timers), servidores falsos y sandboxes.

· Publicado

Creacion de Spies (Creating Spies)

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

Espiar y reemplazar metodos (Spying and Stubbing Methods)

sinon.spy($, 'ajax')
$.ajax()
$.ajax.calledOnce == true
sinon.stub($, 'ajax', function () { /* ... */ }) // Funcion de implementacion opcional
$.ajax.calledWithMatch({ url: '/x' })
$.ajax.restore()

Propiedades de Spies y Stubs (Spy and Stub Properties)

spy
  .args        //=> [ [..], [..] ] un arreglo por llamada
  .thisValues
  .returnValues
  .called      //=> true
  .notCalled
  .callCount
  .calledOnce
  .calledTwice
  .calledThrice
  .getCalls()   //=> Arreglo de objetos de llamada
  .getCall(0)
  .firstCall

Stubs anonimos (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) // Retorna el 1er argumento
  .callsArg(0)

Temporizadores simulados (Fake Timers)

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

Servidor simulado (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 simulado (Fake XHR)

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

Aislamiento con Sandboxes

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

Referencias relacionadas

Temas relacionados