Writing a basic Jest unit test
Jest fundamentals.
import the function, group cases with describe, define each case with it or test, assert with expect and a matcher like toBe, covering normal and edge inputs.
WHAT THIS TESTS Whether you can structure a minimal, correct Jest test and choose the right matcher, including edge cases.
A GOOD ANSWER COVERS First you import the function under test from utils.js. describe groups related test cases under a label, usually the function name, which keeps output readable. Each individual case uses it (or its alias test), which takes a descriptive name and a callback containing the actual test. Inside the callback you call the function with chosen inputs and assert the result using expect with a matcher: toBe for primitive equality, toEqual for deep object or array equality, and others like toThrow for error cases. A good unit test covers the normal case plus edge cases such as empty input or unusual characters, and each test should be independent so order does not matter. You run them with the jest command.
COMMON WRONG ANSWERS Forgetting to import the function, writing a test body with no expect call so nothing is actually asserted, using toBe for object comparison (which fails on reference inequality), or only testing the happy path.
LIKELY FOLLOW-UPS toBe versus toEqual, testing thrown errors, beforeEach setup, and why tests should be independent.
ONE CONCRETE EXAMPLE import { formatTitle } from './utils'; describe('formatTitle', () => { it('capitalizes the first letter', () => { expect(formatTitle('hello')).toBe('Hello'); }); it('handles an empty string', () => { expect(formatTitle('')).toBe(''); }); }); The describe block names the unit, each it states an expectation, and expect with toBe asserts the exact return value for both a normal and an edge input.
Read the original → jestjs.io
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.