A Frontend Team Cut Its Unit Tests by 78% and Production Defects Didn't Budge
Should Frontend Teams Write Unit Tests at All?
Author: ErpanOmer
Hello everyone 😃
Let me state this up front: this article is not trying to convince you to stop writing tests.
What I want to talk about is something else. Last year our team made a decision that many people thought was crazy: we deleted more than 1,800 of the 2,300+ unit test cases in our frontend repository. After the deletion we observed for a full six months, and the number of production defects barely changed.
When I presented this conclusion at our department's weekly meeting, the reactions on the testers' faces were priceless, and our backend colleagues thought we were messing around 🤷♂️.
But the data is there. So today I'll walk through the whole thing: the background, what we deleted, what we kept, and the pitfalls you need to think through before deleting anything.
A Repository with High Coverage
Our team has 9 frontend developers, maintaining a SaaS admin console and a merchant portal. The stack is React + TypeScript, with Vitest + Testing Library.
Two years ago, management set a technical KPI: frontend unit test coverage must be no lower than 75%. It was written into the quarterly OKR, and a coverage gate was added to CI; anything below the threshold blocks the merge request.
Once the metric was set, everyone cooperated. Within six months, coverage went from around 20% to 78%, and the number of test cases jumped to over 2,300. The coverage curve on our report looked beautiful.
But what the team actually felt was a different story:
The last one is the most damaging. When a team's first reaction to a test failure is to modify the test, that test suite has already lost its reason to exist 😖.
We Started with a Data Review
Deleting tests on impulse would be irresponsible. So before we touched anything, I spent two weeks pulling a year of CI logs and Git history and ran some statistics.
The counting rule was simple: over the past 12 months, for every merge request that caused CI test failures, how was it finally resolved?
The results:
| Resolution after test failure | Count | Percentage |
|---|---|---|
| Modified test code to fit the new implementation | 271 | 86.9% |
| Test was flaky, passed on rerun | 22 | 7.0% |
| Test caught a real bug, business code modified | 19 | 6.1% |
| Total | 312 | 100% |
Out of 312 test failures, only 19 actually caught a real bug.
And the distribution of those 19 is more interesting. I looked at each one, and 17 of them were concentrated in three types of modules: amount/price calculation, permission/role checks, and date/timezone handling. The remaining 2 were in a form validation utility function.
As for the 1,800+ test cases covering UI component rendering, Hooks internal state, and page interaction flows, the number of real bugs they caught over the whole year was 0.
Their only contribution was to make everyone fix a few tests every time they changed code, and to make the coverage report look better.
After this data came out, the internal team discussion reached a conclusion pretty quickly 🤔.
What Tests Did We Delete?
The deleted tests fell into three broad categories, and I'll show a real example from the repo for each (desensitized).
Tests That Assert Implementation Details
This was the largest category. Its typical trait: it doesn't test user-observable behavior, but rather how the component is implemented internally.
// Must delete: tests internal component state and call counts, not user-visible results
import { render, screen, fireEvent } from '@testing-library/react';
import { vi } from 'vitest';
import * as api from '@/services/order';
import { OrderFilter } from './OrderFilter';
vi.mock('@/services/order');
describe('OrderFilter', () => {
it('should call fetchOrders with correct params when switching status', () => {
const spy = vi.spyOn(api, 'fetchOrders').mockResolvedValue({ list: [], total: 0 });
render(<OrderFilter />);
fireEvent.click(screen.getByText('Pending Shipment'));
// Asserts call count and parameter structure: any refactor of the request wrapper will break this
expect(spy).toHaveBeenCalledTimes(2);
expect(spy).toHaveBeenLastCalledWith({
status: 'WAIT_SHIP',
page: 1,
pageSize: 20,
sort: undefined,
});
});
it('selected Tab should have active class name', () => {
render(<OrderFilter />);
fireEvent.click(screen.getByText('Pending Shipment'));
// If the designer changes the style spec, this needs to change too
expect(screen.getByText('Pending Shipment').className).toContain('tab-item--active');
});
});
The problem with this kind of test is that it's too tightly coupled to the implementation. When we later migrated our request layer from a hand-written wrapper to TanStack Query, the interface parameter structure changed, and a dozen assertions in this file all broke. But the page behavior itself didn't change at all: users clicked "Pending Shipment" and still saw pending orders.
Snapshot Tests
toMatchSnapshot() is a coverage artifact; a single line covers the entire component tree. Our repo had more than 400 snapshot files.
But snapshot tests in a business project are almost pure burden. When the snapshot changes, CI fails, the developer opens the diff, sees hundreds of lines of DOM structural changes, and nobody actually reviews them line by line. They just run vitest -u to update the snapshots.
In our year-long stats, the rate of updating snapshots after a snapshot failure was 100%. Not once did a snapshot fail because it caught a problem.
Fully Mocked Integration Tests
There was another category, nominally called integration tests, but actually everything was mocked: the API, routing, store, and third-party SDKs. The test was running in a virtual world with no relation to the production environment.
Real production issues, like a backend field changing from number to string, an API timing out under weak network conditions, or a third-party payment callback changing its parameters, none of these tests could catch. Because what they mock is the developer's own mental assumptions.
What We Kept
After the deletion, the repo had about 400 test cases left, and coverage dropped to 31%. But each of these 400 is one we believe must make you stop and look if it fails.
Pure Logic Module Tests
Amount calculation, discount stacking, permission checks, timezone conversion. These modules have clear inputs and outputs, many edge cases, and a mistake means financial loss or privilege escalation.
We didn't just keep these tests; we added many edge cases:
// Price calculation is a high-risk area for financial loss, edge cases must be comprehensive
import { describe, it, expect } from 'vitest';
import { calcPayableAmount, type PriceInput } from './price';
// All amounts are computed in cents (integers) to avoid the 0.1 + 0.2 floating-point problem
interface PriceCase {
name: string;
input: PriceInput;
expected: number; // unit: cents
}
const cases: PriceCase[] = [
{
name: 'no discount, pay original price',
input: { unitPrice: 9990, quantity: 2, coupons: [], memberDiscount: 1 },
expected: 19980,
},
{
name: 'threshold coupon not met, not applied',
input: {
unitPrice: 4990,
quantity: 1,
coupons: [{ type: 'threshold', threshold: 5000, off: 1000 }],
memberDiscount: 1,
},
expected: 4990,
},
{
name: 'member discount first, then threshold coupon: discount first, then check threshold',
input: {
unitPrice: 5500,
quantity: 1,
coupons: [{ type: 'threshold', threshold: 5000, off: 1000 }],
memberDiscount: 0.9, // discounted price is 4950, doesn't meet 5000, coupon not applied
},
expected: 4950,
},
{
name: 'discount produces decimal cents: round down, cannot overcharge users',
input: { unitPrice: 333, quantity: 1, coupons: [], memberDiscount: 0.95 },
expected: 316, // 316.35 -> 316
},
{
name: 'discount amount exceeds order amount: minimum payment is 1 cent, cannot be 0 or negative',
input: {
unitPrice: 800,
quantity: 1,
coupons: [{ type: 'cash', off: 1000 }],
memberDiscount: 1,
},
expected: 1,
},
];
describe('calcPayableAmount', () => {
it.each(cases)('$name', ({ input, expected }) => {
expect(calcPayableAmount(input)).toBe(expected);
});
it('throws when quantity is 0 or negative, does not silently return 0', () => {
expect(() =>
calcPayableAmount({ unitPrice: 100, quantity: 0, coupons: [], memberDiscount: 1 }),
).toThrowError(/quantity/);
});
});
This kind of test almost never needs maintenance. As long as the business rules don't change, it won't fail. When it does fail, it means someone broke the calculation logic, which is exactly the signal we want.
Of the 19 real catches from the earlier statistics, 11 happened in the price and discount file alone.
Interface Contract Validation
Earlier I said fully mocked tests can't catch backend field changes. But that kind of issue accounts for a big share of our production defects.
Our approach was to shift part of the testing budget to runtime contract validation. We used zod to define schemas for core APIs. In development and test environments, a validation failure throws an error directly; in production it degrades to reporting:
// Better than mock tests at catching frontend/backend contract drift
import { z } from 'zod';
import { reportError } from '@/monitor';
const OrderItemSchema = z.object({
orderId: z.string(),
// The backend once changed amount from cents to a string of yuan, causing the page to display wrong
amount: z.number().int().nonnegative(),
status: z.enum(['WAIT_PAY', 'WAIT_SHIP', 'SHIPPED', 'DONE', 'CLOSED']),
createdAt: z.string().datetime(),
});
const OrderListSchema = z.object({
list: z.array(OrderItemSchema),
total: z.number().int().nonnegative(),
});
export type OrderList = z.infer<typeof OrderListSchema>;
const isStrictEnv = import.meta.env.MODE !== 'production';
export function parseContract<T>(
schema: z.ZodType<T>,
raw: unknown,
apiName: string,
): T {
const result = schema.safeParse(raw);
if (result.success) return result.data;
const detail = result.error.issues
.slice(0, 5)
.map((issue) => `${issue.path.join('.')}: ${issue.message}`)
.join('; ');
if (isStrictEnv) {
// In development and test environments, throw immediately so problems surface during integration
throw new Error(`[Contract] ${apiName} response structure does not match contract: ${detail}`);
}
// In production, don't block the page; report and fall back to rendering raw data
reportError({ type: 'api_contract_violation', apiName, detail });
return raw as T;
}
export async function fetchOrderList(params: URLSearchParams): Promise<OrderList> {
const res = await fetch(`/api/orders?${params.toString()}`);
if (!res.ok) throw new Error(`fetchOrderList failed: ${res.status}`);
return parseContract(OrderListSchema, await res.json(), 'fetchOrderList');
}
In the six months after rollout, this contract validation caught 6 backend field changes in the test environment, and reported 2 in production. That payoff is larger than all those hundreds of fully mocked tests combined.
E2E Smoke Tests for Critical Paths
The last piece is smoke tests written with Playwright, covering only 5 critical paths: login, placing an order, payment (sandbox), refund, and product listing.
We're not chasing coverage; we only want to guarantee that if one of these paths breaks, someone knows immediately. We run them in the pre-release environment before every release, and they finish in under 3 minutes 👋.
Pitfalls to Think Through Before Deleting Tests
If you're thinking of going back and deleting some tests after reading this, hold on. We were able to delete with confidence because we did a few things in advance.
Get Data First, Then Cut
Don't delete tests just because you feel they're useless. Every team is different; your tests might have caught real issues.
I wrote a crude script that counted, for each test file, how many times in the past year it was modified in the same commit as its source file. If a test file is changed along with the source code 90% of the time, it's probably testing implementation rather than behavior:
// scripts/test-churn.ts
// Counts co-modification frequency of test and source files to help identify implementation-detail tests
import { execSync } from 'node:child_process';
interface ChurnStat {
testFile: string;
testCommits: number; // commits in which the test file was modified
coChangedCommits: number; // commits in which test and source file were modified together
ratio: number;
}
const SINCE = '12 months ago';
function getCommitFiles(): Map<string, string[]> {
const raw = execSync(
`git log --since="${SINCE}" --name-only --pretty=format:"@@%H" -- src`,
{ encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
);
const commits = new Map<string, string[]>();
let current = '';
for (const line of raw.split('\n')) {
if (line.startsWith('@@')) {
current = line.slice(2);
commits.set(current, []);
} else if (line.trim() && current) {
commits.get(current)!.push(line.trim());
}
}
return commits;
}
function toSourcePath(testFile: string): string {
// Foo.test.tsx -> Foo.tsx, adjust to your naming conventions
return testFile.replace(/\.(test|spec)\.(tsx?|jsx?)$/, '.$2');
}
function analyze(): ChurnStat[] {
const stats = new Map<string, ChurnStat>();
for (const files of getCommitFiles().values()) {
const fileSet = new Set(files);
for (const file of files) {
if (!/\.(test|spec)\.(tsx?|jsx?)$/.test(file)) continue;
const stat = stats.get(file) ?? {
testFile: file,
testCommits: 0,
coChangedCommits: 0,
ratio: 0,
};
stat.testCommits += 1;
if (fileSet.has(toSourcePath(file))) stat.coChangedCommits += 1;
stats.set(file, stat);
}
}
return [...stats.values()]
.filter((s) => s.testCommits >= 5) // too little sample to judge
.map((s) => ({ ...s, ratio: s.coChangedCommits / s.testCommits }))
.sort((a, b) => b.ratio - a.ratio);
}
console.table(
analyze()
.slice(0, 50)
.map((s) => ({
file: s.testFile,
commits: s.testCommits,
coChanged: s.coChangedCommits,
ratio: `${(s.ratio * 100).toFixed(0)}%`,
})),
);
This script is only an aid. The final decision on what to delete still needs CI failure records and manual review. We brought each module's owner to review together, and every deleted file had to be signed off by someone.
After Deleting Tests, Strengthen the Type System
Many implementation-detail tests are essentially compensating for a lack of type safety. For example, testing whether a function crashes when passed undefined, or testing the structure of a component's props.
In the same month we deleted the tests, we turned on strict, noUncheckedIndexedAccess, and exactOptionalPropertyTypes in tsconfig, and cleared more than 300 any entries in the repo. Problems the compiler can catch don't need to be re-caught by tests at runtime.
Production Monitoring Is the Last Line of Defense
Tests can only catch problems you can think of. What actually breaks in production is often what you never imagined.
Alongside deleting tests, we filled in Sentry release health monitoring, API error-rate alerts, and white-screen detection for critical pages. The release process was changed to a 10% canary for 30 minutes before full rollout. When something goes wrong in production, we can detect it within 5 minutes and roll back within 15.
Data Six Months Later
Here's the before/after comparison. Data comes from our defect management system, counting defects encountered by real users outside the test environment:
| Metric | Six months before deletion | Six months after deletion |
|---|---|---|
| Unit test cases | 2316 | 427 |
| Coverage | 78% | 31% |
| CI test time | 14 minutes | 2 minutes 40 seconds |
| Total production defects | 41 | 39 |
| Of which P0 / P1 | 1 / 6 | 1 / 5 |
Production defects stayed roughly flat, and CI time was cut by 80%. Each person on the team saved about 3 to 4 hours per week fixing tests.
I also reviewed the two P0 incidents: the one before deletion was a CDN configuration issue; the one after was a callback anomaly caused by a third-party payment SDK upgrade. Neither was something unit tests could have caught.
Looking back, I think the problem was never testing itself, but that coverage was treated as a goal.
Tests, like all engineering investment, come with costs: the cost of writing, the cost of maintaining, the CI time cost, and the cost of trust erosion as the team gradually becomes numb to red lights. So they should be deployed based on return on investment: write the strictest tests where mistakes are most expensive; for code that changes frequently and where the cost of an error is low, don't weld it down with tests.
Our current principle is simple: for logic involving financial loss, privilege escalation, or data corruption, not a single test can be missing; for pure presentation and interaction layers, we rely on the type system, E2E smoke tests, and production monitoring.
Of course, our team's conclusion may not apply to yours 😃
That's all for today 🙌
If you like my articles, feel free to follow my WeChat public account: [前端技术官] (Frontend CTO).
It mainly covers: Frontend Architecture · AI Programming · Career Insights · Developer Growth
Scan the WeChat QR code to follow 👆
Updates irregularly, no spam, only genuinely useful content.
Top 3 of 4 from juejin.cn, machine-translated. The original thread is authoritative.
Every snapshot failure just gets a direct -u update; that line had me shaking my head. Once coverage gets written into OKRs, tests turn from a defense line into a report.
[watching]
Of course you write them. I used AI to build a mini-program that cures couple disputes and family discord [eating popcorn].
[grinning]