مرجع سريع

ورقة غش Sinon.js للدوال الوهمية والمراقبة

دليل مرجعي شامل لمكتبة Sinon.js: دوال المراقبة Spies، المكونات البديلة Stubs، المحاكاة Mocks، المؤقتات الوهمية، الخوادم الوهمية وإدارة بيئات Sandbox.

· تاريخ النشر

إنشاء دوال المراقبة (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()

محاكاة طلبات XMLHttpRequest (Fake XHR)

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

بيئات العزل الافتراضية (Sandboxes)

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

مراجع ذات صلة

موضوعات ذات صلة