クイックリファレンス

Sinon.js スパイ&スタブ チートシート

Sinon.jsのクイックリファレンス:テストスパイ、スタブ、モック、フェイクタイマー、フェイクサーバー、サンドボックスのライフサイクル管理。

· 公開日

スパイの作成(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) // 第1引数をそのまま返す
  .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()

フェイク XMLHttpRequest(Fake XHR)

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

サンドボックス(Sandboxes)

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

関連リファレンス

関連テーマ