Jest Testing
Framework
Master the fundamentals of automated testing with describe, it, and expect: the building blocks of reliable JavaScript code.
What Is Automated Testing?
Automated testing means writing code that checks your other code. Instead of manually clicking through your app to see if it works, you write small programs (called tests) that run your functions and verify the results are correct.
Why Jest?
The Three Pillars of Jest
describe: Grouping Your Tests
describe creates a labeled block that groups related test cases together. It takes two arguments: a string describing the group and a callback function containing the tests.
it: Defining a Single Test
Each it block (also available as test) represents one specific behavior you are verifying. The string argument should read like a sentence: "it does something."
expect: Making Assertions
expect wraps a value so you can chain a matcher to test it. Matchers are methods like .toBe() or .toEqual() that compare the actual value to an expected value.
toBe vs toEqual
| .toBe() | .toEqual() | |
|---|---|---|
| Comparison | Strict reference (===) | Deep structural |
| Use for | Primitives | Objects & arrays |
| {a:1} === {a:1} | ✕ Fails | ✓ Passes |
| 5 === 5 | ✓ Passes | ✓ Passes |
| Performance | Faster | Slightly slower |
Writing Your First Test: Step by Step
Example 1: Testing an add Function
Example 2: Testing Objects with toEqual
Example 3: Testing Edge Cases
More Useful Matchers
| Matcher | What it checks | Example |
|---|---|---|
| .toContain() | Array/string includes item | expect([1,2]).toContain(1) |
| .toHaveLength() | Array/string length | expect("hi").toHaveLength(2) |
| .toBeNull() | Value is null | expect(null).toBeNull() |
| .toBeDefined() | Value is not undefined | expect(x).toBeDefined() |
| .not | Negates any matcher | expect(3).not.toBe(5) |
How a Test Runs
Common Mistakes
Quick Reference Cheat Sheet
| Concept | Syntax | Purpose |
|---|---|---|
| Group tests | describe("name", fn) | Organize related tests |
| Single test | it("does X", fn) | Define one behavior |
| Assertion | expect(val).matcher() | Verify a result |
| Exact match | .toBe(expected) | Primitives (===) |
| Deep match | .toEqual(expected) | Objects & arrays |
| Negate | .not.matcher() | Invert any assertion |
| Error check | .toThrow(msg?) | Verify error thrown |
Question 1 of 5
What is the purpose of describe() in Jest?
Question 2 of 5
Which matcher should you use to compare two objects with the same properties?
Question 3 of 5
What is wrong with this code?
expect(divide(10, 0)).toThrow("error")
Question 4 of 5
In Jest, it() and test() are:
Question 5 of 5
What happens if an it() block contains no expect() calls?