3.5 KiB
title, comments, description
| title | comments | description |
|---|---|---|
| spy | true |
Wrap a method in a spy in order to record calls to the functions and what arguments the function was called with.
cy.spy returns a Sinon.js spy. All methods found on Sinon.JS spies are supported. cy.spy creates spies in a sandbox, so all spies created are automatically reset/restored between tests without you having to explicitly reset/restore them.
The main difference between cy.spy and cy.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.
Cypress has also built-in sinon-chai support, so any assertions supported by sinon-chai can be used without any configuration.
Unlike most Cypress commands, cy.spy is synchronous and returns a value (the spy) instead of a Promise-like chain-able object.
| Returns | the spy |
cy.spy( object, "method" )
Wraps the method on the object with a spy and returns the spy. See the sinon.js spy docs for methods on the spy.
Usage
Wrap a method with a spy
// assume App.start calls util.addListeners
cy.spy(util, 'addListeners')
App.start()
expect(util.addListeners).to.be.called
Example Recipe
{% note info Using cy.spy %} Check out our example recipe testing spying, stubbing and time {% endnote %}
Alias a spy
Adding an alias using cy.as to spies makes them easier to identify in error messages and Cypress's command log.
const obj = {
foo () {}
}
const spy = cy.spy(obj, 'foo').as('anyArgs')
const withFoo = spy.withArgs('foo').as('withFoo')
obj.foo()
expect(spy).to.be.called
expect(withFoo).to.be.called // purposefully failing assertion
You will see the following in the command log:
Command Log
Create a spy, alias it, and call it
const obj = {
foo () {}
}
const spy = cy.spy(obj, 'foo').as('foo')
obj.foo('foo', 'bar')
expect(spy).to.be.called
The command above will display in the command log as:
When clicking on the spy-1 event within the command log, the console outputs the following:
