Cypress Stub and Spy Not Working Fix
In this tutorial, you'll learn about Cypress Stub and Spy Not Working Fix. We cover key concepts, practical examples, and best practices.
Your cy.stub() doesn't replace the function — or cy.spy() reports 0 calls when the function was definitely called.
The Problem
// WRONG — stub created but never used
const callback = cy.stub();
// callback is a Cypress stub, but it's not attached to anything
myFunction();
expect(callback).to.be.called; // Fails — callback is a detached stub
The stub was created but never connected to the code under test. It's a standalone function that nothing calls.
Step-by-Step Fix
1. Stub object methods
// RIGHT — stub on an object
const logger = {
log: (msg) => console.log(msg),
};
cy.stub(logger, 'log').returns('stubbed');
logger.log('test'); // Uses the stub
expect(logger.log).to.be.calledWith('test');
2. Spy on existing methods
// RIGHT — spy to track calls
const calculator = {
add: (a, b) => a + b,
};
cy.spy(calculator, 'add');
calculator.add(2, 3);
expect(calculator.add).to.be.calledWith(2, 3);
expect(calculator.add).to.have.returned(5);
3. Stub with custom behavior
// RIGHT — stub with implementation
cy.stub(Math, 'random').returns(0.5);
expect(Math.random()).to.equal(0.5);
cy.stub(Date, 'now').returns(1700000000000);
expect(Date.now()).to.equal(1700000000000);
4. Restore stubs and spies
// RIGHT — restore after test
beforeEach(() => {
cy.visit('/');
});
afterEach(() => {
cy.clock().then((clock) => clock.restore());
});
Or use .invoke('restore'):
const stub = cy.stub(console, 'log');
// At end of test:
stub.restore();
Expected output:
✓ stubs object method
✓ spies on method calls
✓ stubs with custom behavior
Prevention Tips
- Attach stubs to existing objects or methods
- Use
cy.stub(obj, 'method')to replace methods - Use
cy.spy(obj, 'method')to monitor calls - Restore stubs/spies after test to avoid leaks
- Use
.returns()for return values,.callsFake()for logic
Common Mistakes with stub spy
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world CYPRESS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro