本文根据 Devhints / Sinon 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2017-10-27。
创建侦探对象 (Spies)
fn = sinon.spy()
fn()
fn.calledOnce == true
fn.callCount == 1
监视 (Spying) / 存根 (stubbing)
sinon.spy($, 'ajax')
$.ajax();
$.ajax.calledOnce == true
sinon.stub($, 'ajax', function () { ... }) // function optional
$.ajax.calledWithMatch({ url: '/x' })
$.ajax.restore()
监视/存根属性
spy
.args //=> [ [..], [..] ] one per call
.thisValues
.returnValues
.called //=> true
.notCalled
.callCount
.calledOnce
.calledTwice
.calledThrice
.getCalls() //=> Array
.getCall(0)
.firstCall
匿名存根
stub = sinon.stub().returns(42)
stub() == 42
stub
.withArgs(42).returns(1)
.withArgs(43).throws("TypeError")
stub
.returns(1)
.throws("TypeError")
.returnsArg(0) // Return 1st argument
.callsArg(0)
模拟日期
sinon.useFakeTimers(+new Date(2011,9,1));
模拟服务器
server = sinon.fakeServer.create()
$.get('/file.json', ...)
server.requests[0].respond(
200,
{ 'Content-Type': 'application/json' },
JSON.stringify({ hello: 'world' })
)
server.restore()
模拟 XHR
xhr = sinon.useFakeXMLHttpRequest()
xhr.restore()
沙盒
beforeEach(function() {
global.sinon = require('sinon').sandbox.create()
})
afterEach(function() {
global.sinon.restore()
})