
Testing Strategies for v0 Applications
Implement comprehensive testing to ensure your v0 applications are reliable and bug-free.
Testing ensures your application works as expected and catches bugs before they reach production. Learn how to implement comprehensive testing strategies in your v0 projects.
Testing Pyramid
Build a solid testing foundation with the right balance of test types:
Test Distribution:
- 70% Unit Tests: Fast, isolated, test individual functions
- 20% Integration Tests: Test feature interactions
- 10% E2E Tests: Test critical user journeys
Unit Testing with Jest and React Testing Library
Component Testing:
```tsx
// components/button.test.tsx
import { render, screen, fireEvent } from '@testing-library/react'
import { Button } from './button'
describe('Button', () => {
it('renders with text', () => {
render(<Button>Click me</Button>)
expect(screen.getByText('Click me')).toBeInTheDocument()
})
it('calls onClick when clicked', () => {
const handleClick = jest.fn()
render(<Button onClick={handleClick}>Click</Button>)
fireEvent.click(screen.getByText('Click'))
expect(handleClick).toHaveBeenCalledTimes(1)
})
it('is disabled when loading', () => {
render(<Button loading>Submit</Button>)
expect(screen.getByRole('button')).toBeDisabled()
})
})
```
Testing Custom Hooks:
```tsx
// hooks/use-counter.test.ts
import { renderHook, act } from '@testing-library/react'
import { useCounter } from './use-counter'
describe('useCounter', () => {
it('increments counter', () => {
const { result } = renderHook(() => useCounter())
act(() => {
result.current.increment()
})
expect(result.current.count).toBe(1)
})
it('resets to initial value', () => {
const { result } = renderHook(() => useCounter(10))
act(() => {
result.current.increment()
result.current.reset()
})
expect(result.current.count).toBe(10)
})
})
```
Mocking Dependencies:
```tsx
// Mock fetch
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ data: 'test' })
})
) as jest.Mock
// Mock Next.js router
jest.mock('next/navigation', () => ({
useRouter: () => ({
push: jest.fn(),
pathname: '/',
}),
useSearchParams: () => new URLSearchParams(),
}))
```
Integration Testing
API Route Testing:
```typescript
// app/api/posts/route.test.ts
import { POST } from './route'
import { createMocks } from 'node-mocks-http'
describe('/api/posts', () => {
it('creates a new post', async () => {
const { req } = createMocks({
method: 'POST',
body: {
title: 'Test Post',
content: 'Test content'
}
})
const response = await POST(req)
const data = await response.json()
expect(response.status).toBe(201)
expect(data.post.title).toBe('Test Post')
})
it('validates required fields', async () => {
const { req } = createMocks({
method: 'POST',
body: { title: '' }
})
const response = await POST(req)
expect(response.status).toBe(400)
})
})
```
Database Integration Tests:
```typescript
import { createClient } from '@supabase/supabase-js'
describe('User operations', () => {
let supabase: ReturnType<typeof createClient>
beforeAll(() => {
supabase = createClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_ANON_KEY!
)
})
afterEach(async () => {
// Clean up test data
await supabase.from('users').delete().eq('email', 'test@example.com')
})
it('creates a user', async () => {
const { data, error } = await supabase
.from('users')
.insert({ email: 'test@example.com', name: 'Test User' })
.select()
.single()
expect(error).toBeNull()
expect(data.email).toBe('test@example.com')
})
})
```
End-to-End Testing with Playwright
Setup:
```typescript
// playwright.config.ts
import { defineConfig } from '@playwright/test'
export default defineConfig({
testDir: './e2e',
use: {
baseURL: 'http://localhost:3000',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
},
webServer: {
command: 'npm run dev',
port: 3000,
reuseExistingServer: !process.env.CI,
},
})
```
User Journey Tests:
```typescript
// e2e/auth.spec.ts
import { test, expect } from '@playwright/test'
test.describe('Authentication', () => {
test('user can sign up and log in', async ({ page }) => {
// Navigate to sign up
await page.goto('/signup')
// Fill form
await page.fill('[name="email"]', 'test@example.com')
await page.fill('[name="password"]', 'SecurePass123!')
await page.click('button[type="submit"]')
// Verify redirect to dashboard
await expect(page).toHaveURL('/dashboard')
await expect(page.locator('h1')).toContainText('Welcome')
// Log out
await page.click('[aria-label="User menu"]')
await page.click('text=Log out')
// Verify redirect to home
await expect(page).toHaveURL('/')
})
test('shows error for invalid credentials', async ({ page }) => {
await page.goto('/login')
await page.fill('[name="email"]', 'wrong@example.com')
await page.fill('[name="password"]', 'wrongpass')
await page.click('button[type="submit"]')
await expect(page.locator('[role="alert"]')).toContainText(
'Invalid credentials'
)
})
})
```
Visual Regression Testing
Playwright Screenshots:
```typescript
test('homepage looks correct', async ({ page }) => {
await page.goto('/')
await expect(page).toHaveScreenshot('homepage.png')
})
```
Performance Testing
Lighthouse CI:
```json
// lighthouserc.json
{
"ci": {
"collect": {
"url": ["http://localhost:3000/"],
"numberOfRuns": 3
},
"assert": {
"assertions": {
"categories:performance": ["error", {"minScore": 0.9}],
"categories:accessibility": ["error", {"minScore": 0.9}]
}
}
}
}
```
Continuous Integration
GitHub Actions Workflow:
```yaml
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 18
- run: npm ci
- run: npm run test
- run: npm run test:e2e
- uses: actions/upload-artifact@v3
if: failure()
with:
name: test-results
path: test-results/
```
Test Coverage:
```json
// package.json
{
"scripts": {
"test:coverage": "jest --coverage",
"test:watch": "jest --watch"
},
"jest": {
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": 80
}
}
}
}
```
Comprehensive testing gives you confidence to ship quickly while maintaining high quality and catching bugs before they reach production.
Need Help with Your v0 Project?
Our team of v0 experts is ready to help you build amazing applications with cutting-edge AI technology.
Get in Touch