스파이 생성 (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 and Stub Properties)
spy
.args //=> 호출당 인자 배열 [ [..], [..] ]
.thisValues
.returnValues
.called //=> true
.notCalled
.callCount
.calledOnce
.calledTwice
.calledThrice
.getCalls() //=> 호출 객체 배열
.getCall(0)
.firstCall
익명 스텁 (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()
})