# Cypress Documentation
# Source: https://raw.githubusercontent.com/cypress-io/cypress-documentation/main/docs/api/commands/stub.mdx
# Path: docs/api/commands/stub.mdx

---
title: 'stub | Cypress Documentation'
description: Replace a function, record its usage and control its behavior in Cypress.
sidebar_label: stub
---

<ProductHeading product="app" />

# stub

Replace a function, record its usage and control its behavior.

`cy.stub()` is a utility function, and is not a Cypress command, query or
assertion. It is not retryable, chainable, or timeout-able.

:::info

**Note:** `.stub()` assumes you are already familiar with our guide:
[Stubs, Spies, and Clocks](/app/guides/stubs-spies-and-clocks)

:::

## Syntax

```javascript
cy.stub()
cy.stub(object, method)
```

### Usage

<Icon name="check-circle" color="green" /> **Correct Usage**

```javascript
cy.stub(user, 'addFriend')
cy.stub(user, 'addFriend').as('addFriend')
```

### Arguments

<Icon name="angle-right" /> **object _(Object)_**

The `object` that has the `method` to be replaced.

<Icon name="angle-right" /> **method _(String)_**

The name of the `method` on the `object` to be wrapped.

<HeaderYields />

- `cy.stub()` is _synchronous_ and returns a value (the stub) instead of a
  Promise-like chain-able object. It can be aliased.
- `cy.stub()` returns a [Sinon.js stub](http://sinonjs.org). All methods found
  on [Sinon.js](http://sinonjs.org) spies and stubs are supported.

## Examples

### Method

#### Create a stub and manually replace a function

```javascript
// assume App.start calls util.addListeners
util.addListeners = cy.stub()

App.start()
expect(util.addListeners).to.be.called
```

#### Replace a method with a stub

```javascript
// assume App.start calls util.addListeners
cy.stub(util, 'addListeners')

App.start()
expect(util.addListeners).to.be.called
```

#### Replace a method with a function

```javascript
// assume App.start calls util.addListeners
let listenersAdded = false

cy.stub(util, 'addListeners').callsFake(() => {
  listenersAdded = true
})

App.start()
expect(listenersAdded).to.be.true
```

#### Specify the return value of a stubbed method

```javascript
// assume App.start calls util.addListeners, which returns a function
// that removes the listeners
const removeStub = cy.stub()

cy.stub(util, 'addListeners').returns(removeStub)

App.start()
App.stop()
expect(removeStub).to.be.called
```

#### Replace built-in window methods like prompt

In end-to-end tests, replacing built-in `window` methods needs to happen _after_
the page is visited, but _before_ the application under test is loaded. You can
do this by stubbing functions inside the [`cy.visit()`](/api/commands/visit)
command `onBeforeLoad` function.

In Component tests, because the page isn't being reloaded, all you need to do is
stub functions before mounting your component.

:::visit-mount-example

```js
-{cy.visit('http://localhost:3000', {
  onBeforeLoad(win) {
    // Stub your functions here
    cy.stub(win, 'prompt').returns('my custom message')
  },
})

App.start()::// Stub your functions here
cy.mount()
cy.stub(window, 'prompt').returns('my custom message')

// After that, mount your component
cy.mount(<MyComponent />)}-

cy.window().its('prompt').should('be.called')
cy.get('.name').should('have.value', 'my custom message')
```

:::

#### Disable logging to Command Log

You can chain a `.log(bool)` method to disable `cy.stub()` calls from being
shown in the Command Log. This may be useful when your stubs are called an
excessive number of times.

```javascript
const obj = {
  foo() {},
}
const stub = cy.stub(obj, 'foo').log(false)
```

#### More `cy.stub()` examples

:::info

[Check out our example recipe testing spying, stubbing and time](/app/references/recipes#Stubbing-and-spying)

:::

### Aliases

You can alias stubs, similar to how [`.as()`](/api/commands/as) works. This can
make your stubs easier to identify in error messages and Cypress's command log,
and allows you to assert against them later using `cy.get()`.

```javascript
const obj = {
  foo() {},
}
const stub = cy.stub(obj, 'foo').as('anyArgs')
const withFoo = stub.withArgs('foo').as('withFoo')

obj.foo()

expect(stub).to.be.called
cy.get('@withFoo').should('be.called') // purposefully failing assertion
```

You will see the following in the command log:

<DocsImage
  src="/img/api/stub/stubs-with-aliases-and-error-in-command-log.png"
  alt="stubs with aliases"
/>

## Notes

### Restores

#### Automatic reset/restore between tests

`cy.stub()` creates stubs in a
[sandbox](http://sinonjs.org/releases/v8/sandbox/), so all stubs created are
automatically reset/restored between tests without you having to explicitly
reset/restore them.

### Differences

#### Difference between cy.spy() and cy.stub()

The main difference between `cy.spy()` and [`cy.stub()`](/api/commands/stub) is
that `cy.spy()` does not replace the method, it only wraps it. So, while
invocations are recorded, the original method is still called. This can be very
useful when testing methods on native browser objects. You can verify a method
is being called by your test and still have the original method action invoked.

## Command Log

**_Create a stub, alias it, and call it_**

```javascript
const obj = {
  foo() {},
}
const stub = cy.stub(obj, 'foo').as('foo')

obj.foo('foo', 'bar')
expect(stub).to.be.called
```

The command above will display in the Command Log as:

<DocsImage src="/img/api/stub/stub-in-command-log.png" alt="Command Log stub" />

When clicking on the `(stub-1)` event within the command log, the console
outputs the following:

<DocsImage
  src="/img/api/stub/inspect-the-stubbed-object-and-any-calls-or-arguments-made.png"
  alt="Console Log stub"
/>

## History

| Version                                    | Changes                   |
| ------------------------------------------ | ------------------------- |
| [0.20.0](/app/references/changelog#0-20-0) | Added `.log(bool)` method |
| [0.18.8](/app/references/changelog#0-18-8) | `cy.stub()` command added |

## See also

- [`.as()`](/api/commands/as)
- [`cy.clock()`](/api/commands/clock)
- [`cy.spy()`](/api/commands/spy)
- [Guide: Stubs, Spies and Clocks](/app/guides/stubs-spies-and-clocks)
- [Recipe: Stubbing, Spying](/app/references/recipes#Stubbing-and-spying)
- [Recipe: Unit Test - Stubbing Dependencies](/app/references/recipes)