Γρήγορη αναφορά

Φύλλο οδηγιών Sinon.js Spies & Stubs

Γρήγορος οδηγός αναφοράς για το Sinon.js: test spies, stubs, mocks, fake timers, fake servers και μέθοδοι κύκλου ζωής sandbox.

· Δημοσιεύτηκε

Δημιουργία Spies (Creating Spies)

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

Παρακολούθηση και αντικατάσταση μεθόδων (Spying and Stubbing Methods)

sinon.spy($, 'ajax')
$.ajax()
$.ajax.calledOnce == true
sinon.stub($, 'ajax', function () { /* ... */ }) // Προαιρετικη συναρτηση υλοποιησης
$.ajax.calledWithMatch({ url: '/x' })
$.ajax.restore()

Ιδιότητες Spy και Stub (Spy and Stub Properties)

spy
  .args        //=> [ [..], [..] ] ενας πινακας ανα κληση
  .thisValues
  .returnValues
  .called      //=> true
  .notCalled
  .callCount
  .calledOnce
  .calledTwice
  .calledThrice
  .getCalls()   //=> Πινακας αντικειμενων κλησεων
  .getCall(0)
  .firstCall

Ανώνυμα 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) // Επιστροφη πρωτου ορισματος
  .callsArg(0)

Εικονικοί χρονοδιακόπτες (Fake Timers)

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

Εικονικός διακομιστής (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 (Fake XHR)

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

Περιβάλλοντα απομόνωσης (Sandboxes)

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

Σχετικές αναφορές

Σχετικά θέματα