Cypress and Jest serve different purposes:

  • Jest is a unit testing framework that allows mocking functions, modules, and variables at runtime.
  • Cypress is an end-to-end testing framework that runs in a browser, which makes it difficult to mock internal variables in runtime like Jest does.

Can Cypress mock internal variables inside a function at runtime?

No, Cypress cannot mock internal variables inside a function at runtime like Jest. It runs in a browser and lacks Jest’s runtime control.

Alternatives in Cypress

1. Stub Functions (cy.stub()) – If the function is accessible on window

cy.window().then((win) => {
  cy.stub(win, 'getActionTypeName').returns('RUNTIME_RESET_TYPE');
});

2. Dependency Injection – Refactor the function to accept dependencies

export const functionBeingTested = (getActionTypeName) => {
  return getActionTypeName();
};

Then in your Cypress test:

cy.wrap(() => 'RUNTIME_RESET_TYPE').as('mockFn');
cy.get('@mockFn').then((mockFn) => {
  expect(functionBeingTested(mockFn)).to.eq('RUNTIME_RESET_TYPE');
});

3. Intercept API Calls (cy.intercept()) – Mock API responses:

cy.intercept('GET', '/api/action-type', { actionType: 'RUNTIME_RESET_TYPE' });

4. Use Environment Variables – Control behavior via Cypress config

Cypress.env('ACTION_TYPE', 'RUNTIME_RESET_TYPE');

Then in your app:

const actionType = Cypress.env('ACTION_TYPE') || getActionTypeName();

Conclusion

While Cypress can’t mock internal variables like Jest, it offers workarounds through stubbing, dependency injection, API interception, and environment variables.

Need Help With React Development?

Work with our skilled React developers to accelerate your project and boost its performance.

Hire Reactjs Developers

Support On Demand!

Related Q&A