Cypress Stubbing – What is it?

On This Page What is Stubbing?What is the Cypress Stub () Method?

March 27, 2026 · 7 min read · Tool Comparison

Cypress Stubbing & # 8211; What is it?

Testing is inherent to modern web development because it control applications act as expected. Due to its speed, reliability, and usability, has turn a best-loved for developers. Cypress & # 8217; s feature to examine via stubbing allows you to simulate certain behaviors within your test without relying on external services or components.

This article dig deeper into what stubbing is in Cypress and how we can use thecy.stub() method.

What is Stubbing?

Stubbing is a examination technique for replacing certain functions or method with versions that return predefined values.

This proficiency do sequestrate the unit under test easier from any external dependencies, like an API, database, or third-party service. This way, it & # 8217; s more controlled and consistent. As a resultant, faster tests are executed. With & # 8220;stubs& # 8221; to name outside your code, the developers are better prepared and can focus on the core application functionality, assuming no variability of those network requests, other constituent, etc.

While stub is useful when external data or functions are not currently available, it is generally recommend to use stub as little as possible because it uses unrealistic information or functionalities.

What is the Cypress Stub () Method?

Cypress provides thecy.stub()method as a built-in tool to create function stubs. This method permit you to replace an existing office with a nub, enabling you to check the function & # 8217; s behavior during the test. Thecy.stub()method is often expend when you need to copy sure behaviors, such as render specific data or tracking how many times a function is called.

The cy.stub () method is typically used to replace a function or object method during a trial:

cy.stub (object, 'method ');

Here, the objectcontains the method you want to stub. & # 8216;method& # 8216; is the method that will be supercede with the stub.

You can also define the demeanor of the stub. For example, you can make the nub homecoming specific values, throw an error, or track call get to it.

const myStub = cy.stub () .returns ('hello '); myStub ();

The stub returns hello in this model.

Read More:

Why is the Cypress Stub () Method used?

The cy.stub () method is used to simplify the testing of functions that interact with external scheme. By supercede these functions with controlled versions (stubs), you can:

  • Eliminate External Dependencies: Isolate your test from international services (like APIs) that may be unreliable or slow.
  • Control Function demeanor: You can manipulate the stub to return different values or simulate different scenarios (for example, success, or failure).
  • Improve Test Reliability: Tests become predictable and deterministic, ensuring consistent results.
  • Track Function Calls: Stubs allow you to verify how often a function was ring and with which parameters.

Read More:

Ways to do Stubbing in Cypress

There are respective methods in Cypress for stubbing, each serving a specific purpose. Here, we will walk through the basic usage ofcy.stub(), cy.intercept (), and cy.spy()to understand how stubbing works in different scenarios.

1. Basic Usage of cy.stub ()

Consider a unproblematic example where we stub a method that fetches user data:

describe ('Stubbing Example ', () = & gt; {it ('stubs a method ', () = & gt; {const userStub = cy.stub () .returns ({gens: 'John ', age: 30}); const getUser = () = & gt; userStub (); expect (getUser ()) .to.deep.equal ({gens: 'John ', age: 30}); expect (userStub) .to.have.been.calledOnce;});});

We created a stub userStub that render a predefined user object. The trial checks that the stub was name once and returns the expected object. The exam will surpass if the nub behaves as expected.

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

2. Stubbing with cy.intercept ()

cy.intercept ()is used for intercepting web requests. It ’ s ideal for assume API responses in a test environment without actually making real asking:

describe ('Intercept Example ', () = & gt; {it ('intercepts an API outcry ', () = & gt; {cy.intercept ('GET ', '/api/user ', {gens: 'Jane ', age: 25}) .as ('getUser '); cy.visit ('/profile '); cy.wait (' @ getUser ') .its ('response.body ') .should ('deep.equal ', {gens: 'Jane ', age: 25});});});

We intercept a GET request to /api/userand retrovert a predefined answer. The test waits for the intercepted call and asserts that the response fit the expected resultant. The API call is intercepted, and the exam confirms the response is as expected.

3. Stubbing with cy.spy ()

A cy.spy()is like to acy.stub(), but instead of replace a function ’ s behavior, it allows you to observe it. You can tag the number of call, arguments, and the homecoming value.

describe ('Spy Example ', () = & gt; {it ('spies on a method ', () = & gt; {const myFunc = cy.spy () .as ('mySpy '); myFunc (1, 2, 3); expect (myFunc) .to.have.been.calledOnceWith (1, 2, 3);});});

The spy is apply to track the method calls and arguments. The test ascertain that the function was called erst with the expected arguments. The spy tail the method call and ensures it was invoked with the correct parameter.

Read More:

Stubbing Functions and Properties Using cy.stub () Command

The cy.stub () bidding can be employ not only for methods but also for properties. For illustration, you can stub an object property to regress a specific value:

const obj = {greet: () = & gt; 'Hello '}; cy.stub (obj, 'greet ') .returns ('Hi ');

In this case, stub the greet method always to return & # 8216;Hi& # 8216; instead of & # 8216;Hello& # 8216;. This is useful when testing components that depend on certain property value.

Common Scenarios for Cypress Stubbing

Here are some common use cases where Cypress stubbing shines:

  • Simulating API Responses: You can stub API calls to return mock datum without actually hitting the backend.
  • Testing Error Handling: Stub functions to sham network failures, timeouts, or error responses, ensuring your app handles them graciously.
  • Controlling Timing: Control the conduct of time-dependent functions, such as timers, to make test fast and more predictable.
  • Isolating Components: Use stub to test individual constituent or functions without relying on external dependencies.

Talk to an Expert

Difference Between Spies and Stubs

While both spies and nub are employ to monitor or replace functions, the key difference lies in their doings:

  • Spies: Track function calls but don ’ t alter the function ’ s deportment. They are used to verify that a function was telephone with specific arguments or the number of times it was name.
  • Stubs: Replace a office ’ s behavior altogether, allowing you to delimit the return value or simulate certain behavior. Stubs provide the desired yield disregarding of how the replaced code is be used.

Difference between Stubbing and Mocking in Cypress

In Cypress testing, & # 8220;stubbing& # 8221; imitate how a dependency would do. It uses predetermined responses to sure inputs so you can get control over the output without including the dependency.

With & # 8220;mocking, & # 8221; you gain better control over the dependance alternate, so you are allowed to set some expected reply and verify interactions like how many times it was called, with what parameters, and in which order of calls.

In a nutshell, stubbing is a lightweight, output-oriented shape of testing, whereas with mocking, you have far more control over the output as easily as the interaction with the dependency.

Read More:

Best Practices for Stubbing in Cypress

The next tips will help you use stub efficaciously for cypress testing:

  • Use Stubs for External Dependencies: Always stub network shout or third-party service to avoid flaky tests.
  • Keep Tests Independent: Avoid reliance on external APIs or databases by using stubbing for predictable doings.
  • Track Function Calls: Use cy.spy () or assertions like cy.stub () .calledOnce to ensure your purpose are being raise correctly.
  • Avoid Overuse: Stubbing should be expend when necessary, but avoid stubbing too many purpose as it can make your trial harder to preserve.

Why Run Cypress Tests on Real Devices?

Testing your web app on existent device is one of the most critical action to see your application behaves right on multiple device and environs. Here is why you must test on real devices:

  • Test in real user weather.
  • Detect ironware and device-specific issue.
  • Ensure .
  • Measure real-world performance metrics.
  • Verify flawless responsive design.
  • Deliver a bland user experience.

While Cypress provide first-class browser examination, it can not match the efficiency of real-world examine on actual devices. allows you to run Cypress tryout on real device in the cloud so that your coating can be thoroughly tested on respective platforms without the complexity of running a device lab or position it up.

You can run and scale your test suite in just one minute and configure the test environs how you desire.

Conclusion

Mastering stub in Cypress allows developers to write more true, efficient, and set-apart trial. Stubbing is vital in achieving ordered and effective trial, whether you & # 8217; re simulating meshing requests, testing erroneousness handling, or isolating specific components.

By following good practices and realise the difference between stub, spies, and mocks, you can ensure your Cypress tests are precise, maintainable, and scalable.

With puppet like, you can run the range of your Cypress tests to real devices, farther enhancing the quality and accuracy of your test suite.

Tags
92,000+ Views

# Ask-and-Contributeabout this theme with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free