The Reality
No, Cypress cannot mock internal variables inside a function at runtime like Jest.
Cypress operates in a browser environment and lacks Jest’s deep runtime control over module internals.
Why This Myth Persists
- Jest is a Node.js-based unit testing framework. It can intercept, replace, or spy on any variable, function, or module because it controls the entire runtime.
- Cypress is an end-to-end (E2E) and component testing tool that runs in a browser context. It can only interact with what’s exposed to the window or via network requests.
- Cypress cannot reach into a function’s closure or internal state and swap out variables at runtime.
What CAN Cypress Do? (The Practical Toolbox)
|
What You Want To Mock |
Jest Approach |
Cypress Alternative(s) |
| Internal variable in a function | jest.spyOn, jest.mock | ❌ Not possible in Cypress |
| Imported module function | jest.mock(‘./module’) | Attach function to window, then use cy.stub(win, ‘fn’) |
| API/network response | jest.fn or msw | cy.intercept() to mock/fake HTTP responses |
| Environment/config value | process.env | Cypress.env() or set in cypress.env.json |
Real-World Cypress Workarounds
When standard mocking fails, use these proven Cypress strategies to control behavior, inject dependencies, and simulate real-world scenarios in your tests.
1. Expose Functions on window for Stubbing
// In your app codewindow.getActionTypeName = getActionTypeName;
// In your Cypress test
cy.window().then((win) => {
cy.stub(win, ‘getActionTypeName’).returns(‘RUNTIME_RESET_TYPE’);
});
You can only stub what’s on the global scope, not internal variables.
2. Dependency Injection
- Refactor your code to accept dependencies as arguments, so you can pass mocks in tests.
Also Read: Best Backend for React
3. Intercept Network Calls
Great for mocking backend data, but not internal logic.
4. Use Environment Variables
const actionType = Cypress.env(‘ACTION_TYPE’) || getActionTypeName();
Pro Tips
- Design for Testability: If you need to mock internals, refactor code to use dependency injection or expose hooks for testing.
- Use Jest for Unit Tests: For fine-grained mocking, stick with Jest for unit/integration tests, and use Cypress for E2E and black-box component tests.
- Combine Approaches: Use Jest for logic, Cypress for user flows and integration.