Sinon.js API Overview

Sinon.js is a standalone Unit Testing library for JavaScript that provides developers with the tools necessary to create Test Double objects. It is designed to work with any testing framework, including Mocha, Jasmine, and Jest, providing a robust set of features for isolating code under test.

Core Functionalities

The library is primarily composed of three types of test doubles:

  • Spies: A Spies object records the arguments, return value, the value of this, and exceptions thrown for all its calls. It is used to verify that a function was called as expected without necessarily replacing its implementation.
  • Stubs: Stubs are Spies with pre-programmed behavior. They are used to replace specific functions to return fixed values, throw errors, or call specific callbacks, which is essential for simulating edge cases or avoiding expensive operations like Database access.
  • Mocks: Mocks are similar to Stubs but come with built-in expectations. They define the expected interactions upfront and will fail the test if those expectations are not met.

Environment Simulation

Beyond basic test doubles, Sinon.js offers advanced utilities for controlling the execution environment. Fake Timers allow developers to wrap the native clock functions (like setTimeout) to synchronously control the passage of time. Furthermore, Fake XHR and Fake Server provide mechanisms to intercept and respond to AJAX and HTTP requests without a network connection.

Detailed technical specifications can be found at the Official Sinon.js Documentation and the project's GitHub Repository.

Related Topics