To wrap a method in a spy, use the cy.spy()
command.
const obj = {
foo () {},
}
const spy = cy.spy(obj, 'foo').as('anyArgs')
obj.foo()
expect(spy).to.be.called
cy.spy()
retries until the
assertions that follow it pass.
const obj = {
foo () {},
}
cy.spy(obj, 'foo').as('foo')
setTimeout(() => {
obj.foo()
}, 500)
setTimeout(() => {
obj.foo()
}, 2500)
cy.get('@foo').should('have.been.calledTwice')
To create a stub and/or replace a function with a stub, use the cy.stub()
command.
let obj = {
foo () {},
}
const stub = cy.stub(obj, 'foo').as('foo')
obj.foo('foo', 'bar')
expect(stub).to.be.called
To control time in the browser, use the cy.clock()
command.
// create the date in UTC so its always the same
// no matter what local timezone the browser is running in
const now = new Date(Date.UTC(2017, 2, 14)).getTime()
cy.clock(now)
cy.visit('http://localhost:8080/commands/spies-stubs-clocks')
cy.get('#clock-div').click()
.should('have.text', '1489449600')
To move time in the browser, use the cy.tick()
command.
// create the date in UTC so its always the same
// no matter what local timezone the browser is running in
const now = new Date(Date.UTC(2017, 2, 14)).getTime()
cy.clock(now)
cy.visit('http://localhost:8080/commands/spies-stubs-clocks')
cy.get('#tick-div').click()
.should('have.text', '1489449600')
cy.tick(10000) // 10 seconds passed
cy.get('#tick-div').click()
.should('have.text', '1489449610')