How to use the Sinon stub() Function?

Learn how to use Sinon’s stub() function to streamline testing, control dependencies, and enhance test reliability and accuracy.

Get Started free
How to use the Sinon stub() Function
Home Guide How to use the Sinon stub() Function?

How to use the Sinon stub() Function?

Testing JavaScript applications involves isolating the units of code to be tested. One such popular technique is stubbing.

Overview

Stubbing helps in replacing functions or methods with fake implementations to control the behavior of certain parts of your code during testing. Sinon.js is a powerful library for creating stubs, spies, and mocks in JavaScript tests.

Why Are Stubs Used?

  • Isolation: Prevents dependencies from affecting test outcomes.
  • Performance: Avoids calling real APIs or database queries.
  • Control: Defines return values, errors, or custom behavior.
  • Simplifying Tests: Makes unit testing more predictable and reliable.

How to Create and Use a Sinon Stub

  • Create a Stub: Use sinon.stub() to replace an object’s method.
  • Configure Behavior: Set return values, throw exceptions or track calls.
  • Invoke the Stubbed Method: Sinon intercepts the call and applies the defined behavior.
  • Restore Original Method: Use stub.restore() to clean up after testing.

This article explores what stubs are, why they’re used, and how to create them with Sinon.js. It also includes installation, common use cases, and best practices for effective testing.

What are Stubs?

In software testing, a stub is a function or object that analyzes the behavior of a real function or method. Instead of executing the real function, a stub replaces it with controlled, predefined behavior, allowing testers to isolate dependencies, control test conditions, and simulate scenarios like errors, timeouts, or specific responses.

Why are Stubs Used?

Stubs are used in unit testing for the following reasons:

  • Isolation: Stubbing helps isolate the unit being tested by replacing dependencies with predictable outputs.
  • Performance: Some dependencies involve heavy computation, external calls, or slow database operations. Stubs can replace these to speed up tests.
  • Control: Stubs let testers control the output of complex functions, making it easier to test edge cases, error handling, and scenarios that are hard to reproduce with real implementation.
  • Simplifying tests: Without stubs, there will be a need to mock or set up real network requests, file systems, or APIs. Stubbing is a simpler and more controlled way of copying these behaviors.

What is the Sinon stub() function?

The stub() function in Sinon.js is used to create stubs for methods or functions in the code. With this function, a user can replace a real function with a fake implementation. The stub() function can:

  • Return predefined values: A user can specify the output of a stubbed function, regardless of the input parameters.
  • Monitor calls: Sinon stubs can be used to track the number of times a function is called, the arguments passed, and more.
  • Simulate errors: A user can configure the stub to throw errors when testing exception-handling scenarios.
  • Restore functionality: After testing, the original function can be restored to prevent any impact on the actual implementation, ensuring tests don’t cause unintended side effects.

Example:

const sinon = require('sinon');

const userService = {

  get_user_data: function(userId) {

console.log('Fetching real data from the database...');

return { id: userId, name: 'Ayush Singh', email: 'thakurayushsingh82@gmail.com' };

  }

};




const stub = sinon.stub(userService, 'get_user_data').returns({ id: 1, name: 'Fake User', email: 'fakeuser@example.com' });




console.log('Before restoring stub:', userService.get_user_data(1));

stub.restore();




console.log('After restoring stub:', userService.get_user_data(1));
Copied

Installing and Setting Up Sinon.js

Before using Sinon, install it in the project. If anyone is working with Node.js, Sinon can be installed using npm:

npm install sinon --save-dev
Copied

Once Sinon is installed, import it into the test files:

const sinon = require('sinon');
Copied

For browser-based testing, include the Sinon.js library by linking to a CDN or downloading it. To directly use it in the browser, add this script tag:

<script src="https://cdn.jsdelivr.net/npm/sinon@latest"></script>
Copied

How to Create and Use a Sinon Stub?

Follow the below-mentioned steps to create and use a sinon stub.

  • Step 1: Use sinon.stub() to create a stub. Users can specify the object and the method to stub.
  • Step 2: Configure the stub’s behavior to return values, throw exceptions, or track its calls.
  • Step 3: Call the method on the object, and Sinon will intercept the call and apply the stubbed behavior.
  • Step 4: After the test, restore the original method to ensure that the rest of the tests or applications are unaffected.

Example:

const sinon = require('sinon');




const myService = {

  fetchData: function(url) {

return 'real data from ' + url;

  }

};

const stub = sinon.stub(myService, 'fetchData');




stub.returns('fake data');

console.log(myService.fetchData('https://example.com'));




stub.restore();

console.log(myService.fetchData('https://example.com'));
Copied

Common Use Cases for Sinon Stubs

Some of the most common use cases for Sinon Stubs are:

  • Mocking HTTP Requests: In such cases where the application interacts with external services via HTTP requests (e.g., fetch() or axios), a user can stub these functions to simulate responses without hitting real APIs.

Example:

const stub = sinon.stub(global, 'fetch').resolves({ data: 'fake data' });
Copied

Using a cloud-based testing platform like BrowserStack Automate, developers can run these stubbed tests in real environments to confirm cross-browser reliability.

Talk to an Expert

  • Analyzing Errors: Any user can stub functions to analyze errors (e.g., network failures or unexpected exceptions). This is useful for testing error-handling mechanisms.

Example:

const stub = sinon.stub(myService, 'fetchData').throws(new Error('Network error'));
Copied
  • Testing Async Code: For functions that return promises or use async operations, stubs help produce various responses like success, failure, or timeouts.

Example:

const stub = sinon.stub(myService, 'fetchData').resolves('fake data');
Copied

With BrowserStack, developers can execute their JavaScript test suites on real devices and browsers, ensuring that asynchronous operations function correctly in different environments.

BrowserStack Automate Banner

  • Database Interaction: If the code directly interacts with a database, a user can stub the database queries to avoid real database access during testing.

Best Practices to Use Sinon Stubs

Some of the best practices for using Sinon Stubs in unit testing are:

  • Restore Original Methods: Always restore the original method after the test is complete to avoid side effects on other tests. Sinon provides the restore() function to revert the stub to its original state.
Syntax: stub.restore();
Copied
  • Ensure Cross-Browser Reliability: Failing to restore original methods can cause unreliable tests, especially across environments. Running tests on BrowserStack Automate ensures stubbed functions behave consistently across browsers.
  • Avoid Overusing Stubs: While stubs are efficient, overusing them can lead to tests that are directly related to the implementation. Use them when necessary, but avoid stubbing functions that are irrelevant to the test at hand.
  • Track Calls Using calledOnce, calledWith, and Other Methods: Use Sinon’s built-in methods to confirm that the stubs are called the right number of times or with the correct arguments. This improves the accuracy of tests.
  • Limit the Scope of Stubs: Stubbing at the global level can introduce unintended side effects. It’s better to stub methods locally or within specific test cases to avoid impacting other tests.

Conclusion

The stub() function in Sinon.js is highly efficient and makes unit testing easier and more effective by isolating dependencies and controlling their behavior. By using stubs, any user can check conditions and scenarios that might be difficult to reproduce with real implementations.

Ensuring that stubbed tests work reliably across real browsers and devices is crucial. With BrowserStack Automate, developers can run their JavaScript tests on a real device cloud, validating their application’s behavior in real-world conditions.

Try BrowserStack Now

Tags
Automation Testing Cross browser testing