{"library":"sinon","title":"Sinon.JS Test Spies, Stubs, and Mocks","description":"Sinon.js is a widely used, standalone, and test framework-agnostic JavaScript library providing test spies, stubs, and mocks for robust unit testing. The current stable version is 21.1.2. It maintains a consistent release cadence, frequently publishing updates and bug fixes across major versions. Key differentiators include its non-global pollution approach, ease of integration with any testing framework (like Mocha, Jest, or QUnit), and built-in fakes for browser APIs such as timers (setTimeout, setInterval) and XMLHttpRequest. It is designed to be easy to use and requires minimal setup, allowing developers to isolate and test specific units of code effectively by controlling their dependencies and behavior.","language":"javascript","status":"active","last_verified":"Sun Apr 19","install":{"commands":["npm install sinon"],"cli":null},"imports":["import sinon from 'sinon';","import sinon from 'sinon'; sinon.stub(obj, 'method');","import sinon from 'sinon'; const clock = sinon.useFakeTimers();"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import sinon from 'sinon';\n\n// Simulate an external API dependency\nclass ExternalAPI {\n  async getData(): Promise<string> {\n    // In a real application, this would make an actual network call\n    return Promise.resolve('Real Data From Server');\n  }\n}\n\n// Our code under test that depends on ExternalAPI\nclass MyService {\n  constructor(private api: ExternalAPI) {}\n\n  async processData(): Promise<string> {\n    const data = await this.api.getData();\n    return data.toUpperCase();\n  }\n}\n\nasync function runExample() {\n  const api = new ExternalAPI();\n  const service = new MyService(api);\n\n  // Create a stub for the API's getData method\n  const getDataStub = sinon.stub(api, 'getData');\n\n  // Configure the stub to return a predictable, mock value\n  getDataStub.resolves('Mocked Data');\n\n  // Call the method under test, which now uses the stubbed getData\n  const result = await service.processData();\n\n  console.log('Processed Result:', result); // Expected output: MOCKED DATA\n  console.log('getData was called once:', getDataStub.calledOnce); // Expected output: true\n\n  // Restore the original method to clean up after the test\n  getDataStub.restore();\n}\n\nrunExample().catch(console.error);","lang":"typescript","description":"Demonstrates stubbing an asynchronous dependency's method and verifying its interaction for isolated unit testing.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}