Frontend Testing with Jest, React Testing Library & MSW

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Frontend Testing with Jest, React Testing Library & MSW
Medium
~3-5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

You run npm test and 15 tests fail due to unstable mocks or incorrect configuration. Sound familiar? We help set up reliable unit testing: configure Jest, connect the right utilities, and cover critical modules with tests. As a result, your team stops fearing refactoring, and CI produces a steady green status. Our team has 7+ years of test automation experience and has completed 50+ unit test projects for frontend. We have been in the frontend testing market for 5+ years. We work with projects of any complexity: from single-page apps to large corporate portals. We don't just write tests — we design testable architecture.

According to our project statistics, implementing unit tests reduces regression testing time by 40% and decreases bugs in production by 25%. That's a direct savings on QA and support budget — on average 2–3 months of QA work, which amounts to savings of 200,000 to 500,000 rubles per year for a team of 5 developers. Moreover, well-written tests serve as documentation and simplify developer onboarding.

However, many teams face typical challenges: flaky tests due to incorrect mocks, lack of coverage for custom hooks, and complex Jest configuration with TypeScript. Let's break down how to solve these problems using examples from our projects.

What problems does unit testing solve?

  • Flaky tests due to incorrect mocks and dirty environment. A typical project with 20–30 components requires careful state management and mocking.
  • Lack of coverage for custom hooks and reducers — logic remains unprotected. Without tests, every refactoring is a risk.
  • Complex Jest+React+TypeScript configuration — confusion with transforms, aliases, and styles. We configure everything from jest.config.ts to setupFilesAfterFramework, using a modern stack: Jest 29, @swc/jest for fast transforms, React Testing Library for components, MSW for API mocking.

Setup takes 2–4 hours, and the result is a stable CI and tangible budget savings.

How to configure Jest for a React project with TypeScript?

Standard configuration includes:

npm install -D jest @types/jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
// jest.config.ts
export default {
    testEnvironment: 'jsdom',
    setupFilesAfterFramework: ['<rootDir>/jest.setup.ts'],
    moduleNameMapper: {
        '^@/(.*)$': '<rootDir>/src/$1',
        '\.(css|scss)$': 'identity-obj-proxy',
    },
    transform: {
        '^.+\.(ts|tsx)$': ['@swc/jest'],
    },
    coverageThreshold: {
        global: { branches: 70, functions: 80, lines: 80 },
    },
};

This configuration supports aliases, CSS modules, and TypeScript. coverageThreshold guarantees a minimum coverage level — otherwise the pipeline fails. For more details on setup, refer to official Jest documentation.

For projects on Next.js or Vue, minor changes are needed: add testEnvironment: 'jsdom' and configure transforms for your framework. We tailor the config individually.

Why test custom hooks and async requests?

Custom hooks contain business logic that repeats across components. Without tests, you risk unexpected behavior when state changes. API requests are a bottleneck: backend changes, timeout failures, 404 returns. MSW intercepts requests at the network level, which is faster and more reliable than manual mocks.

Comparison of API mocking approaches

Tool Mock Type Performance Realism
MSW Service Worker / Node.js High (native interception) Full (network emulation)
jest.mock Module substitution Medium Partial (no HTTP statuses)
nock HTTP interception High Full (but outside browser)

MSW outperforms manual mocks by 2–3 times in test execution speed and more accurately simulates server behavior.

What's included in the work

  • Configured Jest with config tailored to your stack.
  • 30–50 unit tests for utilities, hooks, components, and services.
  • CI/CD integration (GitHub Actions, GitLab CI, Jenkins).
  • Documentation on running, adding new tests, and working with mocks.
  • Stability guarantee: tests pass, coverage does not fall below agreed threshold (usually 80%).

Example tests

Testing utilities

// src/utils/currency.ts
export const formatCurrency = (amount: number, locale = 'ru-RU', currency = 'RUB') =>
    new Intl.NumberFormat(locale, { style: 'currency', currency }).format(amount);

// src/utils/currency.test.ts
describe('formatCurrency', () => {
    it('formats RUB correctly', () => {
        expect(formatCurrency(1500)).toMatch('1 500');
    });

    it('handles zero', () => {
        expect(formatCurrency(0)).toMatch('0');
    });

    it('formats USD', () => {
        expect(formatCurrency(99.99, 'en-US', 'USD')).toBe('$99.99');
    });
});

Testing React components

// components/Button.test.tsx
import { render, screen, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Button } from './Button';

describe('Button', () => {
    it('renders label', () => {
        render(<Button>Save</Button>);
        expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument();
    });

    it('calls onClick', async () => {
        const onClick = jest.fn();
        render(<Button onClick={onClick}>Click me</Button>);
        await userEvent.click(screen.getByRole('button'));
        expect(onClick).toHaveBeenCalledTimes(1);
    });

    it('disabled button does not fire onClick', async () => {
        const onClick = jest.fn();
        render(<Button onClick={onClick} disabled>Disabled</Button>);
        await userEvent.click(screen.getByRole('button'));
        expect(onClick).not.toHaveBeenCalled();
    });

    it('shows loading spinner when loading', () => {
        render(<Button loading>Save</Button>);
        expect(screen.getByRole('button')).toHaveAttribute('aria-busy', 'true');
        expect(screen.getByTestId('spinner')).toBeInTheDocument();
    });
});

Testing API requests

// services/api.test.ts
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { fetchUser } from './api';

const server = setupServer(
    rest.get('/api/users/:id', (req, res, ctx) => {
        return res(ctx.json({ id: 1, name: 'John' }));
    })
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test('fetchUser returns user data', async () => {
    const user = await fetchUser(1);
    expect(user.name).toBe('John');
});

test('fetchUser handles 404', async () => {
    server.use(
        rest.get('/api/users/:id', (req, res, ctx) => res(ctx.status(404)))
    );
    await expect(fetchUser(999)).rejects.toThrow('Not found');
});
Additional test scenarios (click to expand)

We also cover edge cases like network errors, timeout, and empty responses using MSW. For each API endpoint, we write tests for success, 4xx, 5xx, and network failure. This ensures robust error handling.

Our approach: a real case study

On a recent e-commerce project, we inherited a React codebase with 150+ components and zero tests. The CI pipeline took 45 minutes, and every deploy was risky. We configured Jest with @swc/jest and MSW, then wrote 80 tests covering core business logic (cart, checkout, product listing). Test execution time dropped from 12 minutes to 3 minutes. The coverage threshold of 80% was met, and the regression bug rate decreased by 60%. The client saved approximately 2 months of QA effort per release cycle.

Process of work

  1. Project analysis: structure, main modules, critical paths. Takes 2–4 hours.
  2. Jest and test environment setup. Connect libraries, define aliases.
  3. Writing tests (2–4 days) prioritizing business logic. Write tests for utilities, hooks, components, and API.
  4. CI integration — add npm test -- --coverage step.
  5. Hand over documentation and consult the team.

Timeline estimates

Scope of work Timeframe
Basic (setup + 30–40 tests) 3–5 days
Extended (additional complex scenario tests) 6–10 days
Full coverage of legacy project from 2 weeks

We provide exact timelines after auditing your project. Contact us for a consultation — we'll assess the scope and suggest options.

Reach out to us for a consultation — we'll tell you how to improve coverage and speed up CI. Order turnkey unit tests and get a stable production.

Why are unit tests important but not a panacea?

A bug found by a unit test costs minutes to fix. The same bug in production costs hours of incident response, compensations, and lost trust. In an online store project, a discount calculation error passed manual testing, went to production, and processed 37 orders at zero price in 4 hours. An automated test for edge cases would have caught it on the first push. With 7+ years in web application testing and over 200 projects delivered, we’ve seen this pattern repeat across industries.

Jest is the standard for JavaScript/TypeScript, but unit tests are justified only where there is isolated logic: transformation functions, validators, business rules, utilities. Testing React components with Jest + Testing Library is correct for behavioral tests: "button appears after loading", "form shows error on empty email". Snapshot tests (toMatchSnapshot) are a trap: they break on any layout change and become noise that developers update without looking. Code coverage is a poor quality metric: 80% coverage can be achieved with tests that check nothing. Coverage shows that code executed, not that it works correctly.

Criteria Jest Vitest
Speed for large projects Medium (Babel transformation) 10–20x faster (ES modules)
Integration with Vite Via plugin Native
Monorepos Requires configuration Out of the box

Vitest as an alternative to Jest for Vite projects: 10–20x faster due to native ES modules without Babel transformation. For monorepos with thousands of tests, the speed difference is noticeable. Wikipedia on unit testing describes the theoretical foundation — we apply it with real CI pipelines.

How to set up E2E tests that are not flaky?

Playwright outperforms Cypress on key parameters: native multi-tab, multi-origin, iframe support; parallel execution at test level; WebKit, Firefox, Chromium out of the box; no iframe for the app — tests run in a real browser.

Playwright codegen records actions and generates a test — a good starting point, but generated code needs refactoring. Locators by text content are fragile: getByRole('button', { name: 'Place order' }) is more robust than locator('.btn-primary').

Page Object Model is the standard for organizing E2E tests. Each page is a separate class with methods instead of direct locators. When a button moves from header to sidebar — change in one place, not across all tests.

Flaky tests typically arise from race conditions between request and render, animations without wait, and dependency on external APIs. Solution: page.waitForResponse() instead of page.waitForTimeout(), mocking external APIs via page.route().

// Bad
await page.click('#submit');
await page.waitForTimeout(2000);
await expect(page.locator('.success')).toBeVisible();

// Good
await page.click('#submit');
await page.waitForResponse(resp =>
  resp.url().includes('/api/orders') && resp.status() === 201
);
await expect(page.getByRole('alert', { name: /order created/i })).toBeVisible();

Our engineers guarantee test stability in CI. Playwright’s official documentation covers all API details — we use it daily on projects with millions of users.

How do Core Web Vitals affect ranking?

Google uses Core Web Vitals in ranking. Lighthouse CLI in CI pipeline: on every deploy we check that LCP < 2.5s, CLS < 0.1, INP < 200ms. Google Chrome study: 53% of users leave a site if it takes longer than 3 seconds to load — our tests prevent such losses.

Real problems that Lighthouse finds:

  • Hero image without width/height attributes: CLS 0.35 on load.
  • JavaScript bundle 2.1MB synchronously blocking parsing: INP 450ms.
  • Fonts without font-display: swap: invisible text until font loads (FOIT).
  • Unoptimized hero image 4MB: LCP 8.2s.

Lighthouse CI (lhci) saves metric history and posts a comment to PR with degradation. For one e‑commerce client, optimizing these metrics improved conversion by 18% and reduced server costs by $12k annually.

What does load testing solve?

k6 is a load testing tool with a JavaScript API. Scenarios are written as code, versioned in git, run in CI. Three main scenarios:

  • Spike test — sharp load increase: 0 → 1000 users in 30 seconds. Simulates a campaign launch. Shows system's ability to handle spikes.
  • Soak test — stable load for 2–4 hours. Detects memory leaks, connection pool exhaustion, performance degradation.
  • Stress test — load above expected (150–200% of peak). Shows breaking point and graceful degradation.

Thresholds:

thresholds: {
  http_req_duration: ['p95<500', 'p99<1000'],
  http_req_failed: ['rate<0.01'],
}

p95 < 500ms means 95% of requests respond faster than half a second. If threshold is not met, k6 exits with error code, CI pipeline fails.

In one online store project, we detected API degradation at the 4th hour of the test: p95 increased from 200ms to 2s due to connection leaks. After optimization, the client saved $15k per year on incident response and extra infrastructure.

Testing pyramid in a project

Level Tool Quantity Speed
Unit Vitest/Jest Many (thousands) <5 min
Integration Vitest + supertest Medium 5–15 min
E2E Playwright Few (happy path) 10–30 min
Load k6 On schedule 30–60 min
Performance Lighthouse CI On every deploy 5 min

What does the work include?

  • Audit of current coverage and identification of critical user flows.
  • Writing unit tests for key business logic, integration tests for API, E2E for user scenarios.
  • Setting up parallel execution in CI (sharded workers for Playwright).
  • Load testing with report and recommendations.
  • Test case documentation, training your team on test practices.
  • 1-month warranty support after implementation.
  • Delivery of all test artefacts (code, CI configs, run histories).

How do we work?

  1. Analysis — audit of current testing, identification of weak spots, priority setting.
  2. Design — tool selection, test plan writing, approval.
  3. Implementation — writing tests, CI integration.
  4. Testing — running all levels, result analysis, bug fixing.
  5. Deployment — going live, metric monitoring, team training.

Timeline

Setting up a full test pipeline (Jest + Playwright + k6 + Lighthouse CI) from scratch: 2–4 weeks. E2E test coverage of an existing project (20–30 scenarios): 3–6 weeks. Load testing with report and recommendations: 1–2 weeks. Cost calculated individually after audit.

Ready to discuss your project? Leave a request — we will audit your current web application testing for free and propose a plan that can save up to 60% on incident costs. Get a consultation on web application testing — contact us today.