Testing in JavaScript
Write automated tests with Jest or Vitest for reliability and refactoring safety.
Project setup (Vitest example)
npm install -D vitest
Add script:
{ "scripts": { "test": "vitest" } }
A simple test
import { describe, it, expect } from 'vitest'
import { sum } from './sum.js'
describe('sum', () => {
it('adds numbers', () => {
expect(sum(2, 3)).toBe(5)
})
})
Async tests
it('fetches data', async () => {
const data = await fetchData()
expect(data.ok).toBe(true)
})
Mocks and spies
vi.mock('./net.js', () => ({ fetchData: vi.fn().mockResolvedValue({ ok: true }) }))
const spy = vi.spyOn(console, 'log')
Jest differences
Jest APIs are similar; configure jest.config.js. For ESM, use native support or transforms.
Coverage
vitest run --coverage
Best practices
- Keep tests deterministic and isolated
- Use factories/fixtures; mock external I/O
- Test behavior and contract; avoid coupling to implementation details
Summary
- Set up Vitest/Jest; write unit and async tests
- Use mocks/spies for isolation; measure coverage