Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the use of sinon.js?
SinonJS provides standalone test spies, stubs and mocks for JavaScript unit testing. It helps create fake objects and functions to isolate and test code in controlled environments.
What is SinonJS?
SinonJS is a testing library that provides utilities for creating test doubles. These help you test code in isolation by replacing dependencies with controlled fake implementations.
Core Features
SinonJS offers three main types of test doubles:
Spies ? Track function calls without changing behavior. They record how functions are called.
Stubs ? Replace functions with controlled implementations. You can define what they return or how they behave.
Mocks ? Combine spies and stubs with expectations. They verify that functions are called in specific ways.
Example: Using Spies
const sinon = require('sinon');
// Original function
function greetUser(name, callback) {
callback(`Hello, ${name}!`);
}
// Create a spy
const spy = sinon.spy();
// Test the function
greetUser("Alice", spy);
console.log("Spy called:", spy.called);
console.log("Call count:", spy.callCount);
console.log("Called with:", spy.firstCall.args[0]);
Spy called: true Call count: 1 Called with: Hello, Alice!
Example: Using Stubs
const sinon = require('sinon');
// Mock API object
const api = {
fetchUser: function(id) {
// This would normally make HTTP request
return { id: id, name: "Real User" };
}
};
// Replace with stub
const stub = sinon.stub(api, 'fetchUser');
stub.returns({ id: 1, name: "Test User" });
// Test code that uses the API
function getUserName(id) {
const user = api.fetchUser(id);
return user.name;
}
console.log("User name:", getUserName(1));
console.log("Stub called:", stub.called);
// Restore original function
stub.restore();
User name: Test User Stub called: true
Example: Using Mocks
const sinon = require('sinon');
const database = {
save: function(data) {
console.log("Saving:", data);
return true;
}
};
// Create mock with expectations
const mock = sinon.mock(database);
mock.expects('save')
.once()
.withArgs({ name: "John" })
.returns(true);
// Code under test
function saveUser(user) {
return database.save(user);
}
// Execute test
const result = saveUser({ name: "John" });
console.log("Save result:", result);
console.log("Expectations met:", mock.verify());
// Clean up
mock.restore();
Save result: true Expectations met: undefined
Key Benefits
SinonJS provides several advantages for testing:
- Isolation ? Test units without external dependencies
- Control ? Define exactly how dependencies behave
- Verification ? Confirm functions are called correctly
- Speed ? Avoid slow operations like HTTP requests or database calls
Common Use Cases
SinonJS is particularly useful for:
- Testing async code without waiting for real operations
- Simulating error conditions
- Verifying function calls and parameters
- Replacing external services in unit tests
Conclusion
SinonJS is essential for JavaScript unit testing, providing spies, stubs, and mocks to test code in isolation. It helps create reliable, fast tests by controlling dependencies and verifying interactions.
