Back to Test Automation
2026-02-125 min read

Stubs (Test Automation)

Learn Stubs (Test Automation) step by step with clear examples and exercises.

Title: Test Automation with JavaScript - Stubs (Part 1)

Why This Matters

In test automation, we often encounter situations where we need to control the behavior of certain functions or APIs that are part of our application under test (AUT). This is where stubs come into play. Stubs allow us to replace real functions with dummy implementations during testing, giving us more control over the test environment and enabling us to isolate individual components for testing.

In this lesson, we will learn about stubs in the context of popular test automation frameworks such as Selenium, Cypress, and Playwright using JavaScript examples. Understanding how to effectively use stubs can help you write more robust tests, reduce test flakiness, and save time during the testing process.

Prerequisites

Before diving into stubs, it's essential to have a basic understanding of the following topics:

  1. JavaScript programming language
  2. Test automation frameworks (Selenium, Cypress, Playwright)
  3. Asynchronous JavaScript concepts (promises, async/await)
  4. Familiarity with npm (Node Package Manager) and package.json file

Core Concept

What is a Stub?

A stub is a placeholder or replacement for an actual function or API call in your application under test. It allows you to control the behavior of that function during testing, providing predictable and consistent results. Stubs can be used to simulate various scenarios, such as network delays, errors, or specific responses from APIs.

Why Use Stubs?

  1. Isolation: By replacing real functions with stubs, we can isolate individual components for testing and ensure that they behave correctly in different scenarios without being affected by external dependencies.
  2. Control: Stubs allow us to control the behavior of functions during testing, making it easier to test edge cases or specific error conditions.
  3. Simplification: Stubbing can help simplify complex test scenarios by removing unnecessary interactions between components and focusing on the component under test.
  4. Speed: Using stubs can significantly speed up test execution time as they eliminate the need for actual network requests, database access, or other resource-intensive operations.

How to Create a Stub?

In JavaScript, you can create stubs using various techniques such as mocking libraries (e.g., Jest, Sinon), or by manually creating functions that mimic the behavior of the function you want to replace. We will focus on using the Sinon library for creating stubs in this lesson.

Worked Example

Let's consider a simple example where we have an API call to fetch data from an external service:

async function getData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}

In this example, we have a getData function that fetches data from an external API and returns it as JSON. To test this function, we could create a stub to simulate the behavior of the external API. Here's how we can do it using Sinon:

const { stub } = require('sinon');

// Create a stub for the fetch function
const fetchStub = stub(global, 'fetch').returns({
json: () => Promise.resolve({ data: 'Test Data' })
});

async function testGetData() {
const result = await getData();
assert.deepEqual(result, { data: 'Test Data' });
}

// Restore the original fetch function after testing
fetchStub.restore();

In this example, we create a stub for the fetch function using Sinon's stub method and replace it with a new implementation that returns a predefined response. We then test our getData function by calling it and asserting that the returned data matches our expected result. Finally, we restore the original fetch function to ensure that it functions correctly outside of our tests.

Common Mistakes

  1. Not properly restoring stubs: Failing to restore stubs after testing can lead to unexpected behavior in subsequent tests or in production code.
  2. Overusing stubs: Using too many stubs can make your tests brittle and difficult to maintain. It's important to find the right balance between using stubs for isolation and testing real functionality.
  3. Not considering edge cases: When creating stubs, it's essential to consider various edge cases and ensure that your stubs handle them appropriately.
  4. Using inappropriate stubbing techniques: Some stubbing techniques may not be suitable for certain scenarios or frameworks. It's important to choose the right technique based on your specific testing needs.
  5. Not verifying the correct behavior of stubs: It's crucial to verify that your stubs are behaving as expected and not introducing unintended side effects.

Practice Questions

  1. How can you create a stub for a function using Sinon?
  2. What are some common scenarios where stubbing can be useful in test automation?
  3. Why is it important to properly restore stubs after testing?
  4. How would you handle an edge case where the external API returns an error instead of data?
  5. Can you think of a situation where using a stub might not be appropriate?

FAQ

--

Q: What's the difference between a mock and a stub?

A: Mocks are more sophisticated than stubs, as they can verify that certain methods were called with specific arguments. Stubs, on the other hand, simply return predefined responses without verifying any method calls.

Q: Can I use Sinon with Selenium or Playwright?

A: Yes, you can use Sinon in combination with test automation frameworks like Selenium and Playwright to create stubs for JavaScript functions and APIs.

Q: How do I handle asynchronous functions when creating stubs?

A: When dealing with asynchronous functions, you should ensure that your stub returns a promise that resolves to the desired response. You can use Sinon's returns method for this purpose.

Q: What are some other mocking libraries available for JavaScript?

A: Some popular mocking libraries for JavaScript include Jest, Mocha with Chai, and Jasmine. Each library has its own unique features and capabilities, so it's essential to choose the one that best fits your testing needs.

Q: Can I use stubs for testing user interactions in a web application using Selenium or Playwright?

A: While stubs can be useful for simulating API responses and other server-side functionality, they are not typically used for testing user interactions directly within a web application. For this purpose, test automation frameworks like Selenium and Playwright provide methods for interacting with the browser and verifying the resulting state of the page.

Stubs (Test Automation) | Test Automation | XQA Learn