jest

Jest

JavaScript testing framework with snapshot testing and built-in mocking

JavaScript
Testing
Default
Used by 1621 projects

Details

Language / Topic
javascriptJavaScript
Category
Testing

Rules

balanced
- Describe related tests in `describe('UserService', () => { ... })` blocks and name each case `it('returns null when user not found', () => { ... })`.
- Use `jest.fn()` for spies and `jest.spyOn(object, 'method').mockReturnValue(value)` for patching existing methods.
- Isolate module dependencies with `jest.mock('../db')` at the file top — Jest hoists mock calls automatically.
- Use `expect(fn).toThrow('message')` to assert thrown errors and `expect(mock).toHaveBeenCalledWith(args)` for call verification.
- Reset mocks between tests with `beforeEach(() => jest.clearAllMocks())` to prevent state leakage.
- Group related tests with `describe('PaymentService', () => { ... })` and write each test case with `it('charges the card when balance is sufficient', async () => { ... })` — test names should read as sentences.
- Mock modules with `jest.mock('../stripe', () => ({ charge: jest.fn().mockResolvedValue({ id: 'ch_123' }) }))` at the top of the file — Jest hoists `jest.mock` calls before imports.
- Use `jest.spyOn(service, 'sendEmail').mockResolvedValue(undefined)` to patch specific methods on real objects without replacing the entire module.
- Assert async operations with `await expect(promise).resolves.toEqual({ id: 1 })` and `await expect(badFn()).rejects.toThrow('Network error')`.
- Use `expect(mock).toHaveBeenCalledTimes(1)` and `expect(mock).toHaveBeenCalledWith({ userId: '42' })` to verify mock interactions.
- Reset mock state with `beforeEach(() => jest.clearAllMocks())` — use `jest.resetAllMocks()` to also reset return values, `jest.restoreAllMocks()` to restore spies.
- Use `jest.useFakeTimers()` with `jest.advanceTimersByTime(ms)` to test debounce, throttle, and setTimeout logic without real delays.