Website review
This review may include AI-generated content and is not individually verified. Domain, certificate and other facts come from the observed data on this page.
What is SinonJS?
SinonJS is a JavaScript library for creating test doubles: stubs, spies, mocks and fake timers. It works alongside any unit testing framework, so it is typically adopted as a complement to tools like Jest, Mocha or QUnit rather than as a replacement for them. See SinonJS.
What it is used for
- Spies record how a function was called without changing its behaviour, which helps verify interactions.
- Stubs replace a function's behaviour, letting you force return values, throw errors or assert call arguments.
- Mocks combine expectations about calls with behaviour, useful when you want a test to fail on unexpected interactions.
- Fake timers control
setTimeout,setIntervaland similar APIs, which suits testing debouncing, polling or time-dependent logic. - Fake servers and XHR/fetch helpers intercept network requests so tests can run without a live backend.
Who it suits and trade-offs
It fits developers writing isolated unit tests in Node.js or the browser, especially when dependencies such as HTTP clients, clocks or third-party modules need to be controlled. The main trade-off is that heavy stubbing can make tests tightly coupled to implementation details, so they break when code is refactored even if behaviour is unchanged. Sinon is unopinionated about assertions and runners, which offers flexibility but means more setup choices than an all-in-one framework.
How do I stub a function with SinonJS?
Stubbing replaces a function's behavior during a test so you can control what it returns and verify how it was called. In SinonJS, the common entry point is sinon.stub(), which works alongside any unit testing framework.
Basic pattern
A typical flow is:
- Identify the object and method you want to replace, for example
api.fetchUser. - Create a stub with
const stub = sinon.stub(api, "fetchUser"). - Configure behavior:
stub.returns({ id: 1 }),stub.resolves(data)for promises, orstub.throws(new Error("fail")). - Run the code under test.
- Assert on the stub, such as
stub.calledOnceorstub.calledWith(42). - Restore the original with
stub.restore()or a sandbox.
Sandboxes and cleanup
For multiple stubs, sinon.createSandbox() groups them so a single sandbox.restore() resets everything. This is suited to test suites where leaked stubs would affect later cases.
Trade-offs
Stubbing isolates the unit under test and makes edge cases like errors or slow responses easy to simulate. However, over-stubbing can couple tests to implementation details, so they break when internals change even if behavior stays correct. Prefer stubbing boundaries such as network calls or clocks, and keep assertions focused on observable outcomes.
The official documentation at SinonJS covers fakes, spies and matchers in more depth.
How do I spy on a method with SinonJS?
To spy on a method with SinonJS, wrap the object's method in sinon.spy(). The spy records how the method is called while letting the original implementation run by default.
Basic pattern
const spy = sinon.spy(object, "method");
object.method(42);
console.log(spy.calledOnce); // true
console.log(spy.calledWith(42)); // true
For a standalone function:
const spy = sinon.spy(myFunction);
What spies capture
- Call count:
called,callCount,calledOnce,calledTwice - Arguments:
calledWith,args,firstCall.args - Context and return value:
thisValue,returned - Call order:
calledBefore,calledAfter
Spying vs. stubbing
sinon.spy() |
sinon.stub() |
|
|---|---|---|
| Calls original | Yes, by default | No, unless you call through |
| Changes behavior | No | Yes |
| Best for | Verifying interactions | Isolating dependencies |
Use a spy when you want to observe a real method without altering it; use a stub when you need to replace the behavior. Both work with any unit testing framework, including Mocha, Jest and QUnit, so you can add them to an existing suite without switching runners.
Restore spies after each test with spy.restore() or a sandbox to avoid leaking state between tests. See SinonJS for the full API.
Can SinonJS be used with any unit testing framework?
SinonJS is designed to be test-framework agnostic. Its stubs, spies, mocks and fake timers are plain JavaScript objects and functions that do not depend on a particular runner's internals. Because of that, it can typically be dropped into suites written for Jest, Mocha, Jasmine, QUnit, Vitest, or a custom harness, as long as the environment supports the JavaScript features Sinon uses.
That flexibility matters when you are:
- Migrating between test runners and want to keep assertion helpers and fake timers working.
- Testing legacy code where the runner is fixed but you need to replace network calls or
Date. - Writing framework-agnostic utility tests that must run in several environments.
The main trade-off is integration depth. Jest, for example, ships its own mocking and timer APIs, so mixing them with Sinon can create confusion about which fake clock or mock registry is active. Sinon also restores behaviour manually, so you usually need sinon.restore() in an afterEach hook; some runners do this automatically for their built-in tools.
For documentation and setup guidance, see SinonJS. If you want to compare it with a runner's native mocking, look at Jest or Mocha.
What is the difference between stubbing, spying, and mocking in SinonJS?
In SinonJS, stubbing, spying and mocking are three related ways to replace or observe behaviour in JavaScript tests. They differ mainly in how much control they give you and what they are designed to verify.
Spies
A spy wraps an existing function and records how it was called without changing its behaviour. You use spies when you want to observe calls, arguments, return values or this context while the real logic still runs. They suit tests that check whether a function was invoked correctly.
Stubs
A stub replaces a function entirely. You control what it returns, what it throws, or how it behaves, and it also records call information like a spy. Stubs are useful for isolating the code under test from dependencies such as network calls, timers or databases, and for forcing specific edge cases.
Mocks
A mock is a fake object with pre-programmed expectations. Instead of asserting after the fact, you set expectations on the mock and then verify them. Mocks suit tests where you want to assert that a set of interactions happened in a specific way, though they can make tests more brittle than stubs.
| Tool | Replaces behaviour | Records calls | Typical use |
|---|---|---|---|
| Spy | No | Yes | Observing real functions |
| Stub | Yes | Yes | Isolating dependencies, forcing outcomes |
| Mock | Yes | Yes, with expectations | Verifying interaction contracts |
All three work with any unit testing framework, so the choice typically depends on whether you need observation, control, or expectation-based verification. See SinonJS for details.
How do I create a mock object with SinonJS?
To create a mock object in SinonJS, you typically use sinon.mock(). A mock wraps an existing object and lets you set expectations about how its methods should be called before the code under test runs.
A minimal pattern looks like this:
const mock = sinon.mock(myObject);
mock.expects("myMethod").once().withArgs("value");
// run code that calls myObject.myMethod("value")
mock.verify();
Key points:
sinon.mock(obj)returns a mock forobj; it does not replace the object itself.mock.expects("method")defines an expectation and returns an expectation object you can refine.- Common refinements include
.once(),.twice(),.never(),.withArgs(...), and.returns(...). mock.verify()checks that all expectations were satisfied; it usually throws if not.mock.restore()removes the mock behavior, typically in cleanup.
Mocks differ from spies and stubs. A spy observes calls without changing behavior by default; a stub replaces behavior. A mock combines replacement with built-in expectations and verification, which suits tests where the interaction contract matters as much as the result.
Because SinonJS works with any unit testing framework, you can use mocks alongside Mocha, Jest, or others, though Jest also offers its own mocking utilities. For full API details, see SinonJS.
User reviews (0)