Overview
Sinon.js is a JavaScript library designed to enhance unit testing by providing standalone test spies, stubs, and mocks. It facilitates the isolation of components during testing, allowing developers to focus on the behavior of a specific unit without interference from its dependencies. This approach supports the creation of more robust and predictable tests.
The library is particularly useful in environments where code relies on external services, database interactions, or complex internal modules that are difficult to control in a test environment. By replacing these dependencies with controlled test doubles, Sinon.js enables developers to simulate various scenarios and verify how the unit under test responds. For instance, when testing a function that makes an HTTP request, Sinon.js can stub the network call to return a predefined response, ensuring that the test's outcome is consistent and not dependent on network availability or server state.
Sinon.js is framework-agnostic, meaning it can be integrated with any JavaScript unit testing framework, such as Mocha, Jest, or Vitest. This flexibility allows teams to adopt Sinon.js without requiring a complete overhaul of their existing testing infrastructure. Its core components—spies, stubs, and mocks—each serve distinct purposes in test double implementation:
- Spies record arguments, return values, and exceptions thrown by functions, allowing testers to assert whether a function was called, how many times, and with what parameters.
- Stubs replace existing functions or methods with controlled versions, enabling the simulation of specific behaviors (e.g., always returning a certain value or throwing an error) and preventing side effects.
- Mocks are entire objects pre-programmed with expectations about how they should be used, throwing errors if those expectations are not met. Mocks are often used for strict behavior verification.
The library's design emphasizes clear separation of concerns, aligning with principles of good unit testing where tests should be fast, isolated, and repeatable. By managing dependencies effectively, Sinon.js helps prevent brittle tests that break due to unrelated changes in other parts of the system or external factors. This contributes to a more efficient development workflow and higher confidence in the codebase's correctness. The Sinon.js documentation provides detailed guides and examples for implementing these test doubles.
Key features
- Test Spies: Monitor function calls, arguments, return values, and exceptions without altering the original function's behavior. Spies are useful for verifying interactions.
- Test Stubs: Replace functions or methods with custom implementations, allowing testers to control behavior, prevent side effects, and simulate specific scenarios (e.g., network errors, successful API responses).
- Test Mocks: Create objects with pre-programmed expectations about method calls and their arguments. Mocks facilitate strict behavior verification, failing tests if expectations are not met.
- Fake Timers: Control the passage of time in tests, allowing synchronous testing of asynchronous code that relies on
setTimeout,setInterval,Date, and other time-based APIs. This feature helps eliminate flakiness in time-sensitive tests. - Fake XHR and Server: Simulate XMLHttpRequest (XHR) and server responses, enabling the testing of client-side code that makes HTTP requests without actual network calls. This ensures consistent and fast API interaction tests.
- Restorable Test Doubles: Automatically restore original functions or methods after tests run, preventing test pollution and ensuring that each test operates in a clean environment.
- Integration with Testing Frameworks: Designed to work seamlessly with popular JavaScript testing frameworks such as Mocha, Jest, and Vitest, providing a flexible toolset for various testing setups.
Pricing
Sinon.js is an open-source library distributed under the BSD-3-Clause license. It is free to use for both personal and commercial projects.
| Service | Cost | Notes |
|---|---|---|
| Sinon.js Library | Free | Open-source, no licensing fees or usage costs. |
Pricing information as of 2026-05-09.
Common integrations
Sinon.js is designed to be framework-agnostic and integrates with various JavaScript testing tools and environments:
- Mocha: Often used together for behavior-driven development (BDD) or test-driven development (TDD) style tests. Sinon.js handles the test doubles, while Mocha provides the test runner and assertion framework. Mocha's documentation includes examples of Sinon.js integration.
- Jest: While Jest has its own powerful mocking capabilities, Sinon.js can still be used alongside it, particularly for its advanced stubbing and fake timer features.
- Vitest: A modern test framework that can leverage Sinon.js for test doubles. Vitest's speed and integration with Vite make it a popular choice for modern JavaScript projects.
- Chai: A popular assertion library often paired with Mocha and Sinon.js. Chai provides readable assertion syntax (e.g.,
expect(spy).to.have.been.calledWith('arg')) that complements Sinon.js spies and stubs. - Browser Environments: Sinon.js can be used directly in browser-based testing setups, allowing for the simulation of browser APIs and network requests.
- Node.js Environments: Fully compatible with Node.js, enabling server-side JavaScript testing with comprehensive control over dependencies.
Alternatives
- Jest: A comprehensive JavaScript testing framework that includes its own built-in mocking, spying, and assertion utilities, often used for React and Node.js applications.
- Mocha: A flexible JavaScript test framework that provides core testing functionality, often paired with assertion libraries like Chai and test double libraries like Sinon.js.
- Vitest: A fast, modern unit test framework powered by Vite, offering a Jest-compatible API and built-in mocking capabilities.
Getting started
To begin using Sinon.js, you first need to install it in your project. This example demonstrates how to install Sinon.js and use a test spy to verify a function call within a simple test scenario. The example assumes you have a test runner such as Mocha or Jest configured, though Sinon.js itself is framework-agnostic.
Installation
Install Sinon.js via npm:
npm install sinon --save-dev
Example: Using a Test Spy
This example shows how to use a Sinon.js spy to verify that a callback function is called correctly.
// app.js
function processData(data, callback) {
// Simulate some processing
const result = data.toUpperCase();
callback(result);
}
// test.js (e.g., using Mocha for structure)
const assert = require('assert');
const sinon = require('sinon');
const { processData } = require('./app');
describe('processData', () => {
it('should call the callback with processed data', () => {
// Create a spy for the callback function
const callbackSpy = sinon.spy();
// Call the function under test with the spy as the callback
processData('hello', callbackSpy);
// Assertions using the spy
assert(callbackSpy.calledOnce, 'Callback should have been called once');
assert(callbackSpy.calledWith('HELLO'), 'Callback should have been called with "HELLO"');
// You can also use Sinon's built-in assertions for readability
// sinon.assert.calledOnce(callbackSpy);
// sinon.assert.calledWith(callbackSpy, 'HELLO');
});
});
In this example:
- We define a simple
processDatafunction that takes some data and a callback. - In the test file, we import
sinonand the function to be tested. - We create a
sinon.spy()to wrap our expected callback. - We call
processData, passing the spy as the callback. - Finally, we use
assert(orsinon.assert) to verify that the spy was called once and with the expected processed data ('HELLO').
This demonstrates how Sinon.js allows you to observe interactions with functions without modifying their original implementation, providing clear and isolated verification of behavior.