Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Công dụng của Sinon.js

Sinon.JS — thư viện **test doubles** (spies, stubs, mocks) cho unit testing JavaScript. Standalone, không phụ thuộc test framework (works với Mocha, Jest, Jasmine, QUnit...).

3 khái niệm cốt lõi

1. Spy (Giám sát)

Function giả ghi lại: được gọi bao nhiêu lần, với args gì, return gì, throw gì.

const spy = sinon.spy(obj, 'method');
obj.method(1, 2);
console.log(spy.callCount); // 1
console.log(spy.args[0]);   // [1, 2]

2. Stub (Thay thế)

Thay thế function thật bằng function giả **có behavior tùy chỉnh** (return value cố định, throw error, call callback...).

const stub = sinon.stub(api, 'fetchUser').resolves({ id: 1, name: 'John' });
// hoặc
stub.withArgs(42).returns({ id: 42 }); // conditional

3. Mock (Giả lập object)

Kết hợp spy + stub cho **toàn bộ object** — set expectation trước, verify sau.

const mock = sinon.mock(obj);
mock.expects('method').once().withArgs(1).returns(42);
obj.method(1);
mock.verify(); // throw nếu expectation không match

Use case

  • Isolate unit test: mock API call, timer, DOM, fs...
  • Test error handling: stub throw error.
  • Verify side effect: spyCalledWith, callCount.

Tài liệu: sinonjs.org