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.
npm install sinonVerified import paths — ran on the pinned version, not inferred.
Demonstrates stubbing an asynchronous dependency's method and verifying its interaction for isolated unit testing.
Consult the v3.0.0 migration guide on sinonjs.org for full details. For most users, continue to access functionalities like `sinon.useFakeXMLHttpRequest()` via the top-level `sinon` object.
Update your code to use `spy.resetHistory()` for clearing call history, arguments, and return values of a spy or stub. Use `spy.restore()` for reverting the original method.
Ensure your project is using Sinon.js v4.1.6 or a later version to avoid issues with `sinon.useFakeServer()`.
Always ensure `clock.restore()` is called in an `afterEach` or `after` hook within your test suite to revert global timers and `Date` to their original implementations.
Ensure Sinon is imported as a default export: `import sinon from 'sinon';` (ESM) or `const sinon = require('sinon');` (CommonJS), and then access `stub` as a property: `sinon.stub()`.Replace all calls to `spy.reset()` with `spy.resetHistory()` to clear the call history, arguments, and return values of a spy or stub. Use `spy.restore()` to revert the original method.
Verify that the method or property you intend to stub (`someMethodName`) exists on the object you are passing to `sinon.stub()`. This often happens with dynamic properties or when stubbing properties on prototypes that haven't been correctly inherited or defined.