Frontend Testing Guide
A comprehensive, opinionated guide to frontend testing with Jest, Testing Library, and Vitest for React and Vue. Covers what to test, what not to test, and how AI changes everything.
Why You Should Care About Testing
Let me be straightforward with you. When I started as a frontend, I thought testing was a waste of time. "I can just click around and see if it works." That was my mindset. Then one of my peers caught a critical bug on our test environment through a GitHub code scanner, a payment validation function that silently accepted negative amounts. It had passed every manual QA check because nobody thought to enter a negative number. If that had reached production, customers could have been credited money on every checkout. That was the moment I understood why testing is important.
Here are the actual benefits of writing tests:
- You refactor without fear. Want to rewrite that messy component? If tests pass, you are good. If they don't, you know exactly what you broke.
- You document behavior. Tests are the best documentation. They tell the next developer (or future you) what the code is supposed to do.
- You catch regressions. That subtle bug where changing the date picker breaks the form submission? A test catches that before your users do.
Cons About Testing
I am not going to pretend testing is all sunshine. Here are the trade offs:
- It takes time upfront. Writing tests adds time to your initial development. There is no way around this.
- Bad tests are worse than no tests. Tests that test implementation details break every time you refactor. Now you are maintaining two codebases.
- False confidence. 100% code coverage means nothing if your tests are bad. You can have full coverage and still ship bugs.
- Learning curve. Each framework has its own quirks. Mocking, async testing, component mounting. It is a lot to learn.
Write Tests After the Feature is Done
This is an opinionated take. Do not write tests while you are still building the feature. I know TDD (Test-Driven Development) has a devoted following, and I respect the discipline behind it. But in the real development world, where requirements shift mid-sprint and designs get revised after stakeholder reviews, writing tests alongside feature code means you end up rewriting both.
Here is what happens in practice when you write tests too early:
- You write a component and its tests.
- The designer says "actually, let us move that button inside the modal."
- You rewrite the component.
- You rewrite the tests.
- The product manager says "we also need a confirmation step."
- You rewrite the component again.
- You rewrite the tests again.
That is not productive. That is busywork.
Instead, here is the workflow I recommend:
- Build the feature first. Get it working. Get it reviewed. Get it to a stable state where the requirements are locked down.
- Then write the tests. At this point, you know exactly what the component does, what the edge cases are, and what the expected behavior should be. Your tests will be accurate and stable.
- Run the tests in CI. From this point forward, any regression will be caught automatically.
Writing tests after the feature stabilizes means you write them once, and they stay relevant. That is the goal.
What to Actually Test
This is where most people go wrong. They either test everything or test nothing. Here is what I think actually matters, ranked by priority:
1. Helpers / Utility Functions
These are the easiest and highest value. Pure functions with clear inputs and outputs. No DOM, no state, no complexity.
export function formatCurrency(amount, currency = 'USD') {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency,
}).format(amount)
}
export function slugify(text) {
return text
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
}import { formatCurrency, slugify } from './format'
describe('formatCurrency', () => {
it('formats USD by default', () => {
expect(formatCurrency(1234.5)).toBe('$1,234.50')
})
it('handles zero', () => {
expect(formatCurrency(0)).toBe('$0.00')
})
it('formats other currencies', () => {
expect(formatCurrency(1000, 'EUR')).toBe('€1,000.00')
})
})
describe('slugify', () => {
it('converts to lowercase kebab-case', () => {
expect(slugify('Hello World')).toBe('hello-world')
})
it('removes special characters', () => {
expect(slugify('Hello! @World#')).toBe('hello-world')
})
})2. Custom Hooks (React) / Composables (Vue)
These contain your business logic. They are reusable. They deserve tests.
import { useState, useCallback } from 'react'
export function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue)
const increment = useCallback(() => setCount(c => c + 1), [])
const decrement = useCallback(() => setCount(c => c - 1), [])
const reset = useCallback(() => setCount(initialValue), [initialValue])
return { count, increment, decrement, reset }
}import { ref } from 'vue'
export function useCounter(initialValue = 0) {
const count = ref(initialValue)
function increment() { count.value++ }
function decrement() { count.value-- }
function reset() { count.value = initialValue }
return { count, increment, decrement, reset }
}And here are the tests for each:
import { renderHook, act } from '@testing-library/react'
import { useCounter } from './useCounter'
describe('useCounter', () => {
it('starts with initial value', () => {
const { result } = renderHook(() => useCounter(10))
expect(result.current.count).toBe(10)
})
it('increments', () => {
const { result } = renderHook(() => useCounter(0))
act(() => result.current.increment())
expect(result.current.count).toBe(1)
})
it('resets to initial value', () => {
const { result } = renderHook(() => useCounter(5))
act(() => result.current.increment())
act(() => result.current.reset())
expect(result.current.count).toBe(5)
})
})import { useCounter } from './useCounter'
describe('useCounter', () => {
it('starts with initial value', () => {
const { count } = useCounter(10)
expect(count.value).toBe(10)
})
it('increments', () => {
const { count, increment } = useCounter(0)
increment()
expect(count.value).toBe(1)
})
it('resets to initial value', () => {
const { count, increment, reset } = useCounter(5)
increment()
reset()
expect(count.value).toBe(5)
})
})Notice how Vue composables are even simpler to test, no renderHook or act wrappers needed. They are just functions that return reactive values.
3. Components
This is where people mess up the most. Do not test that setState was called. Do not test internal state values. Test behavior, not implementation.
export function LoginForm({ onSubmit }) {
return (
<form onSubmit={(e) => {
e.preventDefault()
const formData = new FormData(e.target)
onSubmit({
email: formData.get('email'),
password: formData.get('password'),
})
}}>
<label htmlFor="email">Email</label>
<input id="email" name="email" type="email" required />
<label htmlFor="password">Password</label>
<input id="password" name="password" type="password" required />
<button type="submit">Log in</button>
</form>
)
}<template>
<form @submit.prevent="handleSubmit">
<label for="email">Email</label>
<input id="email" v-model="email" type="email" required />
<label for="password">Password</label>
<input id="password" v-model="password" type="password" required />
<button type="submit">Log in</button>
</form>
</template>
<script setup>
import { ref } from 'vue'
const emit = defineEmits(['submit'])
const email = ref('')
const password = ref('')
function handleSubmit() {
emit('submit', { email: email.value, password: password.value })
}
</script>And the tests:
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { LoginForm } from './LoginForm'
describe('LoginForm', () => {
it('submits with email and password', async () => {
const user = userEvent.setup()
const handleSubmit = jest.fn()
render(<LoginForm onSubmit={handleSubmit} />)
await user.type(screen.getByLabelText('Email'), 'reza@example.com')
await user.type(screen.getByLabelText('Password'), 'password123')
await user.click(screen.getByRole('button', { name: 'Log in' }))
expect(handleSubmit).toHaveBeenCalledWith({
email: 'reza@example.com',
password: 'password123',
})
})
it('requires email field', async () => {
render(<LoginForm onSubmit={jest.fn()} />)
const emailInput = screen.getByLabelText('Email')
expect(emailInput).toBeRequired()
})
})import { render, screen } from '@testing-library/vue'
import userEvent from '@testing-library/user-event'
import LoginForm from './LoginForm.vue'
describe('LoginForm', () => {
it('submits with email and password', async () => {
const user = userEvent.setup()
const { emitted } = render(LoginForm)
await user.type(screen.getByLabelText('Email'), 'reza@example.com')
await user.type(screen.getByLabelText('Password'), 'password123')
await user.click(screen.getByRole('button', { name: 'Log in' }))
expect(emitted().submit[0]).toEqual([
{ email: 'reza@example.com', password: 'password123' },
])
})
})See the pattern? We test the same way regardless of framework. Type something, click something, check the result. That is Testing Library's philosophy: test the way your users use the software.
4. Use Cases / Integration Tests
Individual unit tests are great, but they do not tell you if things work together. Think of it like this: you can test that a car engine works, and the wheels spin, and the steering turns. But if you don't test them together, you might end up with a car that turns left when you steer right.
// A use case test: user adds item to cart and sees updated total
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { CartProvider } from './CartContext'
import { ProductCard } from './ProductCard'
import { CartSummary } from './CartSummary'
function App() {
return (
<CartProvider>
<ProductCard product={{ id: 1, name: 'Shirt', price: 25 }} />
<CartSummary/>
</CartProvider>
)
}
describe('Add to cart flow', () => {
it('updates cart total when adding a product', async () => {
const user = userEvent.setup()
render(<App/>)
expect(screen.getByText('Total: $0.00')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /add to cart/i }))
expect(screen.getByText('Total: $25.00')).toBeInTheDocument()
})
})5. What NOT to Test
- Third-party libraries. Do not test that
axios.getworks. Do not test thatreact-routernavigates. They have their own tests. - Styling. Do not test that a button has
background-color: blue. Use visual regression tools for that (Chromatic, Percy, etc.) - Internal state. Do not test
expect(component.state.isOpen).toBe(true). Test that the dropdown is visible.
Jest vs Vitest
Jest
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterSetup: ['@testing-library/jest-dom'],
transform: {
'^.+\\.(js|jsx)$': 'babel-jest',
},
}Pros:
- Massive ecosystem, tons of resources
- Stable and mature
- Works with everything
Cons:
- Slow. Especially on large projects. Like, painfully slow.
- Config can be a nightmare with ESM, TypeScript, CSS modules, etc.
- Watch mode is decent but not great
Vitest
import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: ['./src/test/setup.js'],
},
})Pros:
- Blazing fast (uses Vite's transform pipeline)
- Jest-compatible API (almost drop-in replacement)
- First-class ESM support
- Watch mode is excellent
- If you already use Vite, zero config headache
Cons:
- Younger ecosystem
- Some edge cases where Jest compatibility breaks
My recommendation: If you are starting a new project, use Vitest. If you have an existing project with Jest and it is working fine, do not migrate for the sake of it.
Both work perfectly fine with Testing Library. The test code looks identical:
// This test works in BOTH Jest and Vitest. Literally the same code.
import { render, screen } from '@testing-library/react'
import { Greeting } from './Greeting'
// Only difference: jest.fn() vs vi.fn()
const mockFn = vi.fn() // Vitest
// const mockFn = jest.fn() // Jest
describe('Greeting', () => {
it('shows the name', () => {
render(<Greeting name="Reza" />)
expect(screen.getByText('Hello, Reza!')).toBeInTheDocument()
})
})Jest Coverage in HTML
Jest has a built-in coverage reporter that can generate a full HTML report. This is incredibly useful for visualizing which lines, branches, and functions are covered by your tests. Here is how to set it up:
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterSetup: ['@testing-library/jest-dom'],
collectCoverage: true,
coverageDirectory: 'coverage',
coverageReporters: ['html', 'text-summary'],
}Run your tests with npx jest --coverage and Jest will generate a coverage/ folder in your project root. Open coverage/index.html in your browser and you will see an interactive dashboard showing:
- File by file breakdown each file in your project with percentage bars for statements, branches, functions, and lines covered.
- Line by line highlighting click any file and you will see the source code with green highlights on covered lines and red highlights on uncovered lines. This makes it immediately obvious which code paths your tests are missing.
- Branch coverage conditional expressions (if/else, ternary, switch) are marked to show which branches were executed and which were not.
- Sortable columns sort by any metric to quickly find the files with the lowest coverage.
Add coverage/ to your .gitignore so the generated report does not get committed to your repository.
Vitest Coverage in HTML
Vitest uses @vitest/coverage-v8 (or @vitest/coverage-istanbul) for code coverage. The HTML output is functionally identical to Jest's coverage report. Here is the setup:
npm install -D @vitest/coverage-v8import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: ['./src/test/setup.js'],
coverage: {
provider: 'v8',
reporter: ['html', 'text-summary'],
reportsDirectory: './coverage',
},
},
})Run npx vitest --coverage and open coverage/index.html. You will get the same interactive report with file-by-file breakdowns, line-level highlighting, and branch coverage visualization. The output format is identical because both Jest and Vitest use the same Istanbul reporting engine under the hood.
One nice bonus with Vitest: if you are running in watch mode, you can add --coverage and it will regenerate the HTML report on every test re-run. This gives you a live feedback loop where you can write a test, save, and immediately refresh the browser to see the coverage change.
Do Not Write Tests in TypeScript
Your test files should be .test.js or .test.jsx, not .test.ts or .test.tsx.
Here is why:
- Tests are consumers, not contracts. Your source code has TypeScript to define contracts. Tests consume those contracts. Adding TypeScript to tests does not make them more correct, it makes them more verbose.
- Type errors in tests are noise. You spend time satisfying the type checker instead of testing behavior.
as unknown as MockedFunction. What does that add to your test's value? Nothing.
- AI token consumption. This is a practical one. When you use AI to generate or modify tests, TypeScript tests consume more tokens for the same logic. Type annotations, generic parameters, type imports, type assertions. All of that is tokens spent on making the compiler happy instead of testing behavior.
- Faster feedback loop. Without TypeScript compilation in tests, your test runner starts faster. In a watch mode workflow where you are running tests constantly, this adds up.
- Tests should be easy to write and easy to read. The whole point of testing is to make development smoother. TypeScript in tests adds friction in exchange for marginal (arguably zero) safety benefit. Your source code types already ensure the API is correct. If you call a function with the wrong arguments in a test, the test will fail. That is the point.
// This is clear, readable, and tests behavior:
it('calculates total with discount', () => {
const result = calculateTotal(100, 'SUMMER20')
expect(result).toBe(80)
})
// vs the TypeScript version that adds nothing:
it('calculates total with discount', () => {
const result: number = calculateTotal(100 as number, 'SUMMER20' as DiscountCode)
expect(result).toBe(80)
})The TypeScript version is not more correct. It is just longer. And when AI generates it, it burns tokens on type annotations that provide zero value in a test file.
Exception: If your test file contains complex test utilities or shared fixtures that other test files import, TypeScript can make sense there. But for regular test files? Plain JavaScript.
Testing in the AI Era
This is where things get interesting. AI has fundamentally changed how we write tests. Let me share some thoughts from actually using AI in my daily workflow.
AI is Great for Generating Tests
AI tools like GitHub Copilot, Claude, and ChatGPT are shockingly good at writing tests. You can paste a component and say "write tests for this" and get 80-90% of the way there. For helpers and utility functions, AI generates near-perfect tests.
This is a good thing. It removes the biggest friction point: the initial boilerplate. Nobody likes writing describe, it, render, expect over and over.
AI + Testing: The Practical Workflow
Here is how I actually use AI for testing today:
- Write the source code yourself (or with AI help, but review it carefully)
- Ask AI to generate the test file. Give it the source file and say "write tests for this, focus on behavior, use Testing Library, plain JavaScript"
- Review the generated tests. AI will miss edge cases specific to your business. Add those manually.
- Use AI to generate test data. Need 50 different user objects for testing? AI is perfect for this.
- Do not let AI write your assertions. AI tends to test implementation details. Always review what it is
expect-ing.
AI Prompt Block
Copy and paste the following block into your AI tool (Claude, ChatGPT, Copilot, Cursor, etc.) to have it follow the testing philosophy from this guide when generating tests for your project (please adjust based on your specific needs):
You are a senior frontend test engineer. Follow these rules strictly when writing tests:
GENERAL RULES:
- Write all test files in plain JavaScript (.test.js or .test.jsx), NOT TypeScript
- Use Testing Library for all component tests (@testing-library/react or @testing-library/vue)
- Use userEvent (not fireEvent) for user interactions
- Test behavior, not implementation details
- Do not test internal state, CSS classes, or component internals
- Do not test third-party libraries (axios, react-router, vue-router, etc.)
- Every test should answer: "does this work from the user's perspective?"
TEST STRUCTURE:
- Use describe blocks grouped by feature or function name
- Use clear it/test descriptions that read like sentences
- Follow Arrange-Act-Assert pattern
- Keep each test focused on one behavior
WHAT TO TEST (priority order):
1. Utility/helper functions — pure functions with clear inputs/outputs
2. Custom hooks (React) or composables (Vue) — business logic
3. Component behavior — user interactions and visible output
4. Integration tests — multiple components working together
5. Edge cases — empty states, error states, boundary values
WHAT NOT TO TEST:
- Trivial components that only render static markup
- Styling or CSS (use visual regression tools instead)
- Third-party library internals
- Implementation details (state values, internal methods, DOM structure)
MOCKING RULES:
- Mock external APIs and network requests
- Mock timers when testing time-dependent behavior
- Do not mock the component being tested
- Prefer dependency injection over module mocking when possible
- Use jest.fn() for Jest or vi.fn() for Vitest
ASSERTIONS:
- Use screen queries: getByRole, getByLabelText, getByText (in that priority order)
- Avoid getByTestId unless there is no semantic alternative
- Use toBeInTheDocument(), toHaveTextContent(), toBeVisible() from jest-dom
- For async operations, use findBy queries or waitFor
REACT SPECIFIC:
- Use renderHook from @testing-library/react for custom hooks
- Wrap state updates in act() when testing hooks
- Use userEvent.setup() at the start of each test
VUE SPECIFIC:
- Import render from @testing-library/vue
- Use emitted() to check emitted events
- Composables can be tested as plain functions (no special wrappers needed)
FORMAT:
- No type annotations in test files
- Use const for all variable declarations
- Group related tests in describe blocks
- Add a brief comment at the top of the test file explaining what is being testedQuick Setup Recipes
React + Vitest + Testing Library
npm install -D vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event jsdom @vitejs/plugin-reactimport { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: ['./src/test/setup.js'],
globals: true,
},
})import '@testing-library/jest-dom'Vue + Vitest + Testing Library
npm install -D vitest @testing-library/vue @testing-library/jest-dom @testing-library/user-event jsdomimport { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
test: {
environment: 'jsdom',
setupFiles: ['./src/test/setup.js'],
globals: true,
},
})React + Jest + Testing Library
npm install -D jest @testing-library/react @testing-library/jest-dom @testing-library/user-event jest-environment-jsdom babel-jest @babel/preset-env @babel/preset-reactmodule.exports = {
testEnvironment: 'jsdom',
setupFilesAfterSetup: ['@testing-library/jest-dom'],
}Summary
- Test helpers and utils first. Highest value, lowest effort.
- Test hooks/composables second. They hold your business logic.
- Test component behavior, not implementation. Use Testing Library.
- Write tests after the feature stabilizes. Do not rewrite tests every time the requirements change.
- Write integration tests for critical user flows. They catch what unit tests miss.
- Use Vitest for new projects, Jest is fine for existing ones. Do not migrate for fun.
- Generate HTML coverage reports. They make gaps in coverage immediately visible.
- Write tests in plain JavaScript, not TypeScript. Save the types for source code.
- Use AI to generate test boilerplate but review the assertions and add business logic tests yourself.
- Testing is not optional. It is how professionals ship software without breaking things.
Start small. Test one utility function today. Then a hook tomorrow. Before you know it, you will wonder how you ever shipped code without tests.
Credits
- Jest Docs Official Jest documentation
- Vitest Docs Official Vitest documentation
- Testing Library Docs The philosophy and API reference for Testing Library
- Kent C. Dodds: "Testing Implementation Details" The article that changed how we think about frontend testing
- Kent C. Dodds: "Write tests. Not too many. Mostly integration." The testing philosophy this guide borrows from
Stay Updated
Get notified when I publish new articles about web development, frontend engineering, and more.
No spam, unsubscribe anytime.