Skip to content

Cypress Component Mock Not Working Fix

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Cypress Component Mock Not Working Fix. We cover key concepts, practical examples, and best practices.

Your component test makes real API calls or renders real child components — the mocks aren't taking effect.

The Problem

// WRONG — external dependency not mocked
import UserProfile from './UserProfile';

cy.mount(<UserProfile userId={1} />);
// Component makes a real fetch call — slow and unreliable

The component calls fetch('/api/user/1') which hits the real server. You need to mock the API or the data fetching hook.

Step-by-Step Fix

1. Mock with cy.intercept

// RIGHT — intercept API calls
import UserProfile from './UserProfile';

cy.intercept('GET', '/api/user/1', {
  body: { id: 1, name: 'Alice' },
}).as('getUser');

cy.mount(<UserProfile userId={1} />);
cy.wait('@getUser');
cy.contains('Alice').should('be.visible');

2. Mock child components

// RIGHT — mock children with cy.stub
import ParentComponent from './ParentComponent';

// Stub the child component if possible through dependency injection
const ChildMock = ({ text }) => <div data-testid="mock-child">{text}</div>;

cy.mount(<ParentComponent childComponent={ChildMock} />);

3. Mock context providers

// RIGHT — mock context
import { AuthContext } from './AuthContext';

const mockUser = { name: 'Alice', role: 'admin' };

cy.mount(
  <AuthContext.Provider value={{ user: mockUser, isAuthenticated: true }}>
    <Dashboard />
  </AuthContext.Provider>
);

4. Mock custom hooks

// RIGHT — mock hook return values
import * as useUserHook from './hooks/useUser';

cy.stub(useUserHook, 'useUser').returns({
  user: { name: 'Bob' },
  loading: false,
  error: null,
});

cy.mount(<UserProfile />);

Expected output:

  ✓ renders with mocked API
  ✓ uses mock context
  ✓ renders with mocked hook

Prevention Tips

  • Use cy.intercept() for API mocking in component tests
  • Pass mock child components as props
  • Wrap with mock context providers
  • Stub custom hooks for controlled behavior
  • Mock error states to test error handling

Common Mistakes with component mock

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

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

### Should I mock API calls or data hooks in component tests?

Mock at the API level (cy.intercept) when testing integration with the data layer. Mock at the hook/context level when testing UI behavior in isolation.

How do I mock third-party libraries?

Stub methods on imported modules: import * as analytics from '@analytics/core'; cy.stub(analytics, 'track').returns(null). Or use cy.intercept for network-based libraries.

Can I mock React.lazy components?

Yes. Mock the lazy-loaded component by replacing the import: cy.stub(React, 'lazy').returns(() => <div>Mocked</div>). Or pre-load the lazy component before mounting.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro