What is the difference between unit, API and end-to-end tests?
Written by Jatin Thacker, Automation Architect · Updated
This answer is one piece of Chapter 29: What to Automate.
- What a Test Is Actually For
- The Cost of a Test Over Its Lifetime
- Where the Check Belongs: Unit, API or UI
- Tests That Never Earn Their Keep
- Answering "Automate Everything"
The difference is how much of the system each test touches. A unit test calls a function and checks what it returns, so a failure points at that function. An API test checks that the server accepts and answers requests correctly. An end-to-end test proves the screens, the server and the browser are joined up, but a failure could come from any of them.
A useful rule from the course: put a check at the lowest level that can still see the behaviour, and use the level above to prove the pieces are connected. Fourteen password rules belong in unit tests; one browser test proves the form shows the message.
Playwright can run all three in one project. The example has one of each. The unit test calls formatInr() with no browser and no network. The API test uses the request fixture to call /api/products and checks the total is 24. The end-to-end test opens the catalogue, adds the grinder and checks the cart total. The timings in the run show the gap: 70ms, 255ms and 1.2s.
import { test, expect } from '@playwright/test';
// A tiny function to unit test: no browser, no network.
const formatInr = (n) => '₹' + n.toLocaleString('en-IN');
test('unit: formatInr formats a price', () => {
expect(formatInr(11900)).toBe('₹11,900');
});
test('API: the products endpoint returns 24 items', async ({ request }) => {
const response = await request.get('/api/products');
await expect(response).toBeOK();
expect((await response.json()).total).toBe(24);
});
test('end to end: the grinder reaches the cart', async ({ page }) => {
await page.goto('/catalog.html?mock=static&seed=42&autologin=1');
await page.locator('article[data-sku="MRD-1003"]')
.getByRole('button', { name: 'Add to cart' }).click();
await expect(page.getByTestId('cart-total')).toHaveText('₹11,900');
});ok 1 › unit: formatInr formats a price (70ms) ok 2 › API: the products endpoint returns 24 items (255ms) ok 3 › end to end: the grinder reaches the cart (1.2s) 3 passed (2.9s)
Related questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free