Jest 03 ๐ Writing Your First Test โ test, expect, and .test.js Files
A Jest test is a file that calls the global test function, passes a name and a callback, and asserts on values with the global expect. The globals are injected by the Jest runtime, which is why a .test.js file needs no imports for test or expect and why a require of Jest’s test functions is unnecessary. The framework discovers the file by its name, runs it in a worker process, and reports the result with the file, the test name, and the line of the failing assertion.
This chapter covers the anatomy of a Jest test file, the test and expect globals, and the file discovery convention that decides what Jest runs. The sections that follow walk through the test case structure, the matcher API, and the naming rules that make a file a test.
Key point: A Jest test file is a *.test.js or *.spec.js file that calls the global test and expect without importing them; a test fails when the callback throws, and an assertion failure is a thrown error from a matcher.
a. The test case structure
test and it are the same function with two names. The first argument is the test name (a string), the second is the test body (a function). The body runs synchronously unless it returns a Promise, in which case Jest waits for the Promise to settle. A test that returns a rejected Promise fails; a test that resolves passes.
// sum.test.js
function sum(a, b) {
return a + b;
}
test("adds 1 + 2 to equal 3", () => {
expect(sum(1, 2)).toBe(3);
});
// `it` is an alias for `test`
it("also adds 1 + 2", () => {
expect(sum(1, 2)).toBe(3);
});
Tests are grouped with describe, which takes a name and a callback. The callback contains the tests, and nested describe blocks create nested groups. The grouping is for organization and for hooks (beforeEach, afterEach) that apply to the tests inside the block.
describe("math", () => {
describe("sum", () => {
test("adds two positives", () => {
expect(sum(1, 2)).toBe(3);
});
test("handles negatives", () => {
expect(sum(-1, -2)).toBe(-3);
});
});
});
A test that throws fails. The throw can be an assertion failure from expect, an explicit throw, or a rejected Promise from an async body. Jest reports the error with the test name, the file, and the line where the failure occurred. A test with no assertions passes, because Jest does not enforce that every test asserts something.
The .test.js and .spec.js suffixes are the discovery convention, not a requirement of the test API. A file named sum.js that contains a test call is not discovered by the default testMatch; a file named sum.test.js is. The testMatch configuration option changes the pattern, but the convention is what most projects follow.
b. The expect API and the matcher set
expect(value) returns an object of matchers. The matcher is called with the expected value, and it either returns normally (pass) or throws an error (fail). The matchers are named for the assertion they make: .toBe() for Object.is equality, .toEqual() for deep equality, .toBeTruthy() for truthiness, .toThrow() for thrown errors, .toMatchSnapshot() for snapshots.
// Primitives: Object.is equality
expect(2 + 2).toBe(4);
expect("hello").toBe("hello");
// Objects and arrays: deep equality
expect({ a: 1 }).toEqual({ a: 1 });
expect([1, 2, 3]).toEqual([1, 2, 3]);
// Truthiness
expect("").toBeFalsy();
expect(1).toBeTruthy();
expect(null).toBeNull();
expect(undefined).toBeUndefined();
// Numbers
expect(10).toBeGreaterThan(5);
expect(0.1 + 0.2).toBeCloseTo(0.3);
// Strings
expect("jest").toMatch(/jes/);
// Errors
expect(() => { throw new Error("boom"); }).toThrow("boom");
// Asymmetric matchers
expect({ id: 1, name: "Ana" }).toEqual({
id: expect.any(Number),
name: expect.stringContaining("An"),
});
The .not property inverts any matcher. The asymmetric matchersโexpect.any(), expect.anything(), expect.stringContaining(), expect.objectContaining(), expect.arrayContaining()โare used inside toEqual to assert on parts of a value.
Jest 30 removed the deprecated matcher aliases: toThrowError is now toThrow, and toReturnWith is now toHaveReturnedWith. A test that still uses the old names fails with an error naming the replacement.
c. File discovery and naming
Jest’s default testMatch is **/__tests__/**/*.[jt]s?(x) and **/?(*.)+(spec|test).[jt]s?(x). A file named sum.test.js, sum.spec.js, sum.test.ts, or sum.spec.tsx is a test; a file named sum.js is not, unless it is inside a __tests__ directory.
src/
sum.js
sum.test.js # discovered
__tests__/
utils.js # discovered (inside __tests__)
helpers.spec.js # discovered
index.js # not discovered
The testMatch and testPathIgnorePatterns options change what is discovered. A project that colocates tests with source uses the default. A project that keeps tests in a separate tests/ directory sets testMatch to **/tests/**/*.test.js or similar.
// jest.config.js
module.exports = {
testMatch: ["**/tests/**/*.test.js"],
testPathIgnorePatterns: ["/node_modules/", "/dist/"],
};
A test file with no tests fails with “Your test suite must contain at least one test.” A test file that imports a module with a side effect runs that side effect at collection time, before any test executes. This is why the jest.mock() call is hoisted to the top of the file by Babel, and why factory functions that reference variables must use the hoisting-compatible pattern.
Complete Example Session
// ============================================
// PART 1: THE MODULE UNDER TEST
// ============================================
// src/math.js
function add(a, b) {
return a + b;
}
function divide(a, b) {
if (b === 0) throw new Error("Division by zero");
return a / b;
}
module.exports = { add, divide };
// ============================================
// PART 2: THE TEST FILE
// ============================================
// src/math.test.js
const { add, divide } = require("./math");
describe("add", () => {
test("adds two positives", () => {
expect(add(1, 2)).toBe(3);
});
it("handles negatives", () => {
expect(add(-1, -2)).toBe(-3);
});
});
describe("divide", () => {
test("divides two numbers", () => {
expect(divide(10, 2)).toBe(5);
});
test("throws on division by zero", () => {
expect(() => divide(1, 0)).toThrow("Division by zero");
});
});
// ============================================
// PART 3: THE ASYMMETRIC MATCHERS
// ============================================
test("object with any id", () => {
const user = { id: 42, name: "Ana" };
expect(user).toEqual({
id: expect.any(Number),
name: expect.stringContaining("An"),
});
});
The parts covered the module under test, the test file with describe/test/it, the error assertion, and the asymmetric matchers.
Quick Reference
Test Functions
| Function | Alias | Purpose |
|---|---|---|
test(name, fn) | it | Declare a test case |
describe(name, fn) | โ | Group tests |
test.skip | it.skip | Skip a test |
test.only | it.only | Run only this test |
test.todo | โ | Mark a test as todo |
Common Matchers
| Matcher | Asserts |
|---|---|
.toBe(v) | Object.is equality |
.toEqual(v) | Deep equality |
.toStrictEqual(v) | Strict deep equality |
.toBeTruthy() / .toBeFalsy() | Truthiness |
.toMatch(re) | String matches regex |
.toThrow(msg) | Function throws |
.toBeCloseTo(n) | Floating-point proximity |
.not | Inverts any matcher |
File Discovery
| Pattern | Matches |
|---|---|
*.test.js | Yes |
*.spec.js | Yes |
*.test.tsx | Yes |
__tests__/*.js | Yes |
*.js (outside __tests__) | No |
Best Practices
โ Do This:
// Use test or it consistently
test("adds", () => { ... }); // โ
// Use toEqual for objects
expect({ a: 1 }).toEqual({ a: 1 }); // โ
// Use asymmetric matchers for partial objects
expect(user).toEqual({ id: expect.any(Number) }); // โ
// Test the throw
expect(() => divide(1, 0)).toThrow("Division by zero"); // โ
โ Don’t Do This:
// Use toBe for objects
expect({ a: 1 }).toBe({ a: 1 }); // always fails // โ
// Forget the arrow wrapper for toThrow
expect(divide(1, 0)).toThrow(); // throws before expect // โ
// Use removed matcher aliases
expect(fn).toThrowError(); // removed in Jest 30 // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
toBe fails on objects | Reference comparison | Use toEqual |
toThrow does not catch | Called the function instead of passing it | Wrap in () => fn() |
| No test suite found | Empty file or no test call | Add at least one test |
| Removed matcher alias | Jest 30 cleanup | Use the new name |
| File not discovered | Naming does not match testMatch | Rename or configure testMatch |
Real-World Examples
1. Basic test
test("adds", () => { expect(1 + 1).toBe(2); });
2. Grouped tests
describe("math", () => { test("adds", () => { ... }); });
3. Deep equality
expect({ a: 1 }).toEqual({ a: 1 });
4. Throw assertion
expect(() => fn()).toThrow("message");
5. Asymmetric matcher
expect(user).toEqual({ id: expect.any(Number) });
6. Skip
test.skip("not ready", () => { ... });
7. Only
test.only("focus", () => { ... });
8. Todo
test.todo("implement later");
9. Regex match
expect("jest").toMatch(/jes/);
10. Floating point
expect(0.1 + 0.2).toBeCloseTo(0.3);
Visual
Test File Anatomy
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ math.test.js โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ // no import of test/expect โ โ
โ โ const { add } = require("./math") โ โ
โ โ โ โ
โ โ describe("add", () => { โ โ
โ โ test("adds", () => { โ โ
โ โ expect(add(1, 2)).toBe(3) โ โ
โ โ }) โ โ
โ โ }) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ Globals injected by Jest runtime โ
โ Discovered by *.test.js pattern โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Matcher Selection
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PRIMITIVE OBJECT โ
โ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โ
โ โ toBe โ โ toEqual โ โ
โ โ Object.is โ โ deep equality โ โ
โ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ ERROR PARTIAL โ
โ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โ
โ โ toThrow(() => fn)โ โ expect.any() โ โ
โ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Discovery
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ INCLUDED EXCLUDED โ
โ math.test.js math.js โ
โ math.spec.js node_modules/ โ
โ __tests__/math.js dist/ โ
โ math.test.tsx coverage/ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Test function | test(name, fn) / it(name, fn) |
| Grouping | describe(name, fn) |
| Assertion | expect(value).matcher(expected) |
| Primitive equality | .toBe() (Object.is) |
| Deep equality | .toEqual() |
| Error assertion | .toThrow() with wrapper |
| Inversion | .not |
| File pattern | *.test.* / *.spec.* / __tests__/ |
Key takeaways:
- A Jest test is a file that calls the global
testandexpect. The globals are injected by the runtime, so no imports are needed. The test fails when the callback throws, and an assertion failure is a throw from a matcher. toBeis for primitives;toEqualis for objects.toBeusesObject.is, so two structurally equal objects fail it.toEqualdoes deep equality and is the correct matcher for objects and arrays.toThrowneeds the function, not the call.expect(fn()).toThrow()callsfnbeforeexpectcan catch the throw. The wrapperexpect(() => fn()).toThrow()is the correct form.- The file name determines discovery. Jest runs
*.test.*,*.spec.*, and files inside__tests__/. A file with tests but no matching name is never collected. - Jest 30 removed the deprecated matcher aliases.
toThrowErroristoThrow, andtoReturnWithistoHaveReturnedWith. A test that uses the old names fails with an error naming the replacement.
Remember: A Jest test is a small program that either returns normally or throws. test and expect are globals, the file name is the discovery mechanism, and the matcher is the assertion. Use toBe for primitives, toEqual for structures, and toThrow with the arrow wrapper for errors. Name the file .test.js or .spec.js, put it next to the source or in __tests__/, and let the thrown assertion be the failure signal.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!