Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 30 ยท Getting Started

Your First Jest Test

Write your first Jest test: create a function, add a .test.js file, use test() and expect().toBe(), run npm test and learn to read a passing and failing report.

The best way to understand Jest is to write one test and run it. In this lesson you will create a tiny function, write a test for it, run Jest from the command line, and then break the function on purpose to see what a failure looks like. Reading failure output well is the most useful skill in testing, because that is what you will stare at most of the time.

If you have not yet seen what Jest is made of, start with What Is Jest?.

Real versus stand-in. The files and commands below are real Jest usage, shown read-only because the site cannot run Node packages. The TryIt blocks use a small stand-in test and expect that print output in the same shape as Jest's, so you can experiment with the same ideas live.

Step 1: the code to test

Create a file named sum.js:

JavaScript
function sum(a, b) {
  return a + b;
}

module.exports = sum;

This uses CommonJS (module.exports), which Jest runs without extra setup. If your project uses import and export, you need a transform such as Babel, or Jest's experimental ES module mode; we cover that in TypeScript, Babel and CI.

Step 2: the test file

Create sum.test.js in the same folder:

JavaScript
const sum = require("./sum");

test("adds 1 + 2 to equal 3", () => {
  expect(sum(1, 2)).toBe(3);
});

Three pieces make up this test:

  • test(name, fn) registers a test. The name is a sentence describing the behavior. The function holds the test body.
  • expect(value) wraps the actual result. It returns an object full of matchers.
  • .toBe(3) is a matcher. It compares with Object.is, so it is exact equality for primitives such as numbers and strings.

Notice that you did not require test or expect. Jest provides them as globals in every test file.

Step 3: run it

Add the script to package.json if you have not already:

JSON
{
  "scripts": {
    "test": "jest"
  }
}

Then run:

Terminal
npm test

Jest prints a report along these lines (exact wording, timing and symbols vary by version and terminal):

TEXT
 PASS  ./sum.test.js
  โœ“ adds 1 + 2 to equal 3 (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.4 s
Ran all test suites.

The report has two layers. The top lists each test suite (one file) with PASS or FAIL, and every test inside it. The bottom summarizes counts across the whole run. "Snapshots" will matter later, in Snapshot Testing.

Reading a failure

Now change sum so it has a bug:

JavaScript
function sum(a, b) {
  return a - b;
}

Run npm test again. The report looks like this:

TEXT
 FAIL  ./sum.test.js
  โœ• adds 1 + 2 to equal 3 (3 ms)

  โ— adds 1 + 2 to equal 3

    expect(received).toBe(expected) // Object.is equality

    Expected: 3
    Received: -1

      3 | test("adds 1 + 2 to equal 3", () => {
    > 4 |   expect(sum(1, 2)).toBe(3);
        |                     ^
      5 | });

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total

Read it from the top:

  1. expect(received).toBe(expected) names the matcher and says which side is which. Received is the value your code produced; expected is the value you wrote in the matcher.
  2. // Object.is equality tells you how the comparison works.
  3. Expected: 3 and Received: -1 show the two values.
  4. The code frame points at the exact line, with a caret under the matcher call.

Get into the habit of reading Expected and Received first. Nine times out of ten they tell you what went wrong before you even open the code.

Try the same flow

This stand-in prints results in the same layout as Jest. The first sum is deliberately wrong. Fix the function (change - to +) and run it again.

JS A Jest-shaped test report

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the second test passes even though sum is broken. 0 - 0 and 0 + 0 are both 0. A test only proves what it actually checks. That is why we pick inputs that would reveal a wrong implementation, not just any inputs.

Adding more tests

A test file can hold as many tests as you like. A good first batch covers a normal case, an edge case and an unusual case:

JavaScript
const sum = require("./sum");

test("adds positive numbers", () => {
  expect(sum(1, 2)).toBe(3);
});

test("adds a negative number", () => {
  expect(sum(5, -8)).toBe(-3);
});

test("adds zero", () => {
  expect(sum(7, 0)).toBe(7);
});

Each test should be independent: it must pass or fail no matter what order the others run in. We look at organizing tests in describe, it and Test Organization.

The shape of every test

Almost every test you will ever write has three beats, sometimes called arrange, act, assert:

  1. Arrange the inputs or the situation.
  2. Act by calling the code under test.
  3. Assert that the result is what you expect.

Try writing a second stand-in test where each beat sits on its own line. Writing the three beats separately makes a test far easier to read.

JS Arrange, act, assert

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What if a test file has no tests?

Jest fails a test file with the message "Your test suite must contain at least one test". An empty or misnamed file is therefore noticed immediately. And if no test files match at all, Jest exits with an error unless you pass --passWithNoTests, which prevents a silent "everything is fine" when your naming is wrong.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In expect(sum(1, 2)).toBe(3), which part is the matcher?

    expect() wraps the actual value and returns an object of matchers. toBe is the matcher that compares the received value with 3 using Object.is.
  2. 2. In a failure report, what does Received mean?

    Received is the actual value passed to expect(). Expected is the value you gave to the matcher.
  3. 3. Which file name will Jest run by default?

    Files ending in .test.js or .spec.js (and files in tests folders) match the default test patterns.
  4. 4. A test for sum(0, 0) passes even if sum subtracts instead of adding. What does this show?

    0 - 0 and 0 + 0 are both 0, so that input cannot tell the two implementations apart. Pick inputs where the right and wrong answers differ.

Summary

  • A test file ends in .test.js (or .spec.js) and uses test(name, fn) with expect(value).matcher(expected).
  • toBe checks exact equality with Object.is.
  • npm test runs the jest script and prints PASS or FAIL for every file, plus totals.
  • In a failure, read Expected and Received first, then the highlighted code line.
  • Write each test as arrange, act, assert, and choose inputs that can really expose a bug.

Next: describe, it and Test Organization.