Referință rapidă

Ghid rapid Sinon.js Spies & Stubs

Ghid rapid de referinta pentru Sinon.js: test spies, stubs, mocks, cronometre simulate, servere simulate si medii izolate sandbox.

· Publicat

Crearea spionilor (Creating Spies)

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

Spionarea si inlocuirea metodelor (Spying and Stubbing Methods)

sinon.spy($, 'ajax')
$.ajax()
$.ajax.calledOnce == true
sinon.stub($, 'ajax', function () { /* ... */ }) // Functia de implementare este optionala
$.ajax.calledWithMatch({ url: '/x' })
$.ajax.restore()

Proprietati Spy si Stub (Spy and Stub Properties)

spy
  .args        //=> [ [..], [..] ] un tablou pentru fiecare apel
  .thisValues
  .returnValues
  .called      //=> true
  .notCalled
  .callCount
  .calledOnce
  .calledTwice
  .calledThrice
  .getCalls()   //=> Tablou de obiecte de apel
  .getCall(0)
  .firstCall

Stub-uri anonime (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) // Returneaza primul argument
  .callsArg(0)

Cronometre simulate (Fake Timers)

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

Server simulat (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 simulat (Fake XHR)

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

Medii izolate (Sandboxes)

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

Referinte conexe

Subiecte conexe