essential-test-patterns

1
0
Source

GROWI testing patterns with Vitest, React Testing Library, and vitest-mock-extended.

Install

mkdir -p .claude/skills/essential-test-patterns && curl -L -o skill.zip "https://mcp.directory/api/skills/download/4091" && unzip -o skill.zip -d .claude/skills/essential-test-patterns && rm skill.zip

Installs to .claude/skills/essential-test-patterns

About this skill

GROWI Testing Patterns

GROWI uses Vitest for all testing (unit, integration, component). This skill covers universal testing patterns applicable across the monorepo.

Test File Placement (Global Standard)

Place test files in the same directory as the source file:

src/components/Button/
├── Button.tsx
└── Button.spec.tsx       # Component test

src/utils/
├── helper.ts
└── helper.spec.ts        # Unit test

src/services/api/
├── pageService.ts
└── pageService.integ.ts  # Integration test

Test Types & Environments

File PatternTypeEnvironmentUse Case
*.spec.{ts,js}Unit TestNode.jsPure functions, utilities, services
*.integ.tsIntegration TestNode.js + DBAPI routes, database operations
*.spec.{tsx,jsx}Component Testhappy-domReact components

Vitest automatically selects the environment based on file extension and configuration.

Vitest Configuration

Global APIs (No Imports Needed)

All GROWI packages configure Vitest globals in tsconfig.json:

{
  "compilerOptions": {
    "types": ["vitest/globals"]
  }
}

This enables auto-import of testing APIs:

// No imports needed!
describe('MyComponent', () => {
  it('should render', () => {
    expect(true).toBe(true);
  });

  beforeEach(() => {
    // Setup
  });

  afterEach(() => {
    // Cleanup
  });
});

Available globals: describe, it, test, expect, beforeEach, afterEach, beforeAll, afterAll, vi

Type-Safe Mocking with vitest-mock-extended

Basic Usage

vitest-mock-extended provides fully type-safe mocks with TypeScript autocomplete:

import { mockDeep, type DeepMockProxy } from 'vitest-mock-extended';

// Create type-safe mock
const mockRouter: DeepMockProxy<NextRouter> = mockDeep<NextRouter>();

// TypeScript autocomplete works!
mockRouter.asPath = '/test-path';
mockRouter.query = { id: '123' };
mockRouter.push.mockResolvedValue(true);

// Use in tests
expect(mockRouter.push).toHaveBeenCalledWith('/new-path');

Complex Types with Optional Properties

interface ComplexProps {
  currentPageId?: string | null;
  currentPathname?: string | null;
  data?: Record<string, unknown>;
  onSubmit?: (value: string) => void;
}

const mockProps: DeepMockProxy<ComplexProps> = mockDeep<ComplexProps>();
mockProps.currentPageId = 'page-123';
mockProps.data = { key: 'value' };
mockProps.onSubmit?.mockImplementation((value) => {
  console.log(value);
});

Why vitest-mock-extended?

  • Type safety: Catches typos at compile time
  • Autocomplete: IDE suggestions for all properties/methods
  • Deep mocking: Automatically mocks nested objects
  • Vitest integration: Works seamlessly with vi.fn()

React Testing Library Patterns

Basic Component Test

import { render } from '@testing-library/react';
import { Button } from './Button';

describe('Button', () => {
  it('should render with text', () => {
    const { getByText } = render(<Button>Click me</Button>);
    expect(getByText('Click me')).toBeInTheDocument();
  });

  it('should call onClick when clicked', async () => {
    const onClick = vi.fn();
    const { getByRole } = render(<Button onClick={onClick}>Click</Button>);

    const button = getByRole('button');
    await userEvent.click(button);

    expect(onClick).toHaveBeenCalledTimes(1);
  });
});

Testing with Jotai (Global Pattern)

When testing components that use Jotai atoms, wrap with <Provider>:

import { render } from '@testing-library/react';
import { Provider } from 'jotai';

const renderWithJotai = (ui: React.ReactElement) => {
  const Wrapper = ({ children }: { children: React.ReactNode }) => (
    <Provider>{children}</Provider>
  );
  return render(ui, { wrapper: Wrapper });
};

describe('ComponentWithJotai', () => {
  it('should render with atom state', () => {
    const { getByText } = renderWithJotai(<MyComponent />);
    expect(getByText('Hello')).toBeInTheDocument();
  });
});

Isolated Jotai Scope (For Testing)

To isolate atom state between tests:

import { createScope } from 'jotai-scope';

describe('ComponentWithIsolatedState', () => {
  it('test 1', () => {
    const scope = createScope();
    const { getByText } = renderWithJotai(<MyComponent />, scope);
    // ...
  });

  it('test 2', () => {
    const scope = createScope(); // Fresh scope
    const { getByText } = renderWithJotai(<MyComponent />, scope);
    // ...
  });
});

Async Testing Patterns (Global Standard)

Using act() and waitFor()

When testing async state updates:

import { waitFor, act } from '@testing-library/react';
import { renderHook } from '@testing-library/react';

test('async hook', async () => {
  const { result } = renderHook(() => useMyAsyncHook());

  // Trigger async action
  await act(async () => {
    result.current.triggerAsyncAction();
  });

  // Wait for state update
  await waitFor(() => {
    expect(result.current.isLoading).toBe(false);
  });

  expect(result.current.data).toBeDefined();
});

Testing Async Functions

it('should fetch data successfully', async () => {
  const data = await fetchData();
  expect(data).toEqual({ id: '123', name: 'Test' });
});

it('should handle errors', async () => {
  await expect(fetchDataWithError()).rejects.toThrow('Error');
});

Advanced Assertions

Object Matching

expect(mockFunction).toHaveBeenCalledWith(
  expect.objectContaining({
    pathname: '/expected-path',
    data: expect.any(Object),
    timestamp: expect.any(Number),
  })
);

Array Matching

expect(result).toEqual(
  expect.arrayContaining([
    expect.objectContaining({ id: '123' }),
    expect.objectContaining({ id: '456' }),
  ])
);

Partial Matching

expect(user).toMatchObject({
  name: 'John',
  email: 'john@example.com',
  // Other properties are ignored
});

Test Structure Best Practices

AAA Pattern (Arrange-Act-Assert)

describe('MyComponent', () => {
  beforeEach(() => {
    vi.clearAllMocks(); // Clear mocks before each test
  });

  describe('rendering', () => {
    it('should render with default props', () => {
      // Arrange: Setup test data
      const props = { title: 'Test' };

      // Act: Render component
      const { getByText } = render(<MyComponent {...props} />);

      // Assert: Verify output
      expect(getByText('Test')).toBeInTheDocument();
    });
  });

  describe('user interactions', () => {
    it('should submit form on button click', async () => {
      // Arrange
      const onSubmit = vi.fn();
      const { getByRole, getByLabelText } = render(
        <MyForm onSubmit={onSubmit} />
      );

      // Act
      await userEvent.type(getByLabelText('Name'), 'John');
      await userEvent.click(getByRole('button', { name: 'Submit' }));

      // Assert
      expect(onSubmit).toHaveBeenCalledWith({ name: 'John' });
    });
  });
});

Nested describe for Organization

describe('PageService', () => {
  describe('createPage', () => {
    it('should create a page successfully', async () => {
      // ...
    });

    it('should throw error if path is invalid', async () => {
      // ...
    });
  });

  describe('updatePage', () => {
    it('should update page content', async () => {
      // ...
    });
  });
});

Common Mocking Patterns

Mocking SWR

vi.mock('swr', () => ({
  default: vi.fn(() => ({
    data: mockData,
    error: null,
    isLoading: false,
    mutate: vi.fn(),
  })),
}));

Mocking Modules

// Mock entire module
vi.mock('~/services/PageService', () => ({
  PageService: {
    findById: vi.fn().mockResolvedValue({ id: '123', title: 'Test' }),
    create: vi.fn().mockResolvedValue({ id: '456', title: 'New' }),
  },
}));

// Use in test
import { PageService } from '~/services/PageService';

it('should call PageService.findById', async () => {
  await myFunction();
  expect(PageService.findById).toHaveBeenCalledWith('123');
});

Mocking Specific Functions

import { myFunction } from '~/utils/myUtils';

vi.mock('~/utils/myUtils', () => ({
  myFunction: vi.fn().mockReturnValue('mocked'),
  otherFunction: vi.fn(), // Mock other exports
}));

Mocking CommonJS Modules with mock-require

IMPORTANT: When vi.mock() fails with ESModule/CommonJS compatibility issues, use mock-require instead:

import mockRequire from 'mock-require';

describe('Service with CommonJS dependencies', () => {
  beforeEach(() => {
    // Mock CommonJS module before importing the code under test
    mockRequire('legacy-module', {
      someFunction: vi.fn().mockReturnValue('mocked'),
      someProperty: 'mocked-value',
    });
  });

  afterEach(() => {
    // Clean up mocks to avoid leakage between tests
    mockRequire.stopAll();
  });

  it('should use mocked module', async () => {
    // Import AFTER mocking (dynamic import if needed)
    const { MyService } = await import('~/services/MyService');

    const result = MyService.doSomething();
    expect(result).toBe('mocked');
  });
});

When to use mock-require:

  • Legacy CommonJS modules that don't work with vi.mock()
  • Mixed ESM/CJS environments causing module resolution issues
  • Third-party libraries with complex module systems
  • When vi.mock() fails with "Cannot redefine property" or "Module is not defined"

Key points:

  • ✅ Mock before importing the code under test
  • ✅ Use mockRequire.stopAll() in afterEach() to prevent test leakage
  • ✅ Use dynamic imports (await import()) when needed
  • ✅ Works with both CommonJS and ESModule targets

Choosing the Right Mocking Strategy

// ✅ Prefer vi.mock() for ESModules (simplest)
vi.mock('~/modern-module', () => ({
  myF

---

*Content truncated.*

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

641968

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

590705

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318395

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

450339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.