DEV Community

Cover image for How to Write Your First Unit Test in Node.js Using Jest
Synfinity Dynamics Pvt Ltd
Synfinity Dynamics Pvt Ltd

Posted on

How to Write Your First Unit Test in Node.js Using Jest

TL;DR: To write your first unit test in Node.js with Jest, install Jest with npm install --save-dev jest, write a small pure function, create a matching *.test.js file that uses describe, test, and expect, then run it with npx jest. That's it you have a working test suite.

If you're new to testing, unit tests can feel intimidating at first. But once you write one, you'll realize it's just regular JavaScript with a few new keywords. This guide walks you through creating your first Jest unit test in Node.js, from setup to running your first passing (and failing) test.

What Is Jest and Why Use It?

Jest is a JavaScript testing framework maintained by Meta that lets you write and run unit tests with almost zero configuration. It bundles a test runner, an assertion library, and mocking utilities into a single package, so you don't need to install and wire together separate tools.

Key features:

  • Zero-config - works out of the box for most Node.js and JavaScript projects
  • Built-in assertions - no need for a separate library like Chai
  • Mocking support - easily fake functions, modules, and timers
  • Snapshot testing - capture output and detect unexpected changes
  • Fast and parallelized - runs test files in parallel by default

Jest vs Mocha: Quick Comparison

Feature Jest Mocha
Assertion library Built-in (expect) Requires Chai or similar
Mocking Built-in Requires Sinon
Configuration Minimal / zero-config More manual setup
Snapshot testing Yes No (needs plugin)
Popularity for Node.js Very high High

For beginners, Jest is usually the easier starting point because everything you need ships in one package.

Prerequisites

Before you start, make sure you have:

  • Node.js installed (version 14 or higher recommended)
  • Basic familiarity with JavaScript functions and npm
  • A project folder to work in

Step 1: Set Up Your Project

Create a new folder and initialize a Node.js project:

mkdir jest-first-test
cd jest-first-test
npm init -y
Enter fullscreen mode Exit fullscreen mode

Install Jest as a dev dependency:

npm install --save-dev jest
Enter fullscreen mode Exit fullscreen mode

Open package.json and add a test script:

{
  "scripts": {
    "test": "jest"
  }
}
Enter fullscreen mode Exit fullscreen mode

Now you can run your tests with npm test instead of typing the full command every time.

Step 2: Write a Simple Function to Test

Unit tests work best on small, pure functions functions that take an input and return an output without side effects. Create a file called sum.js:

// sum.js
function sum(a, b) {
  return a + b;
}

module.exports = sum;
Enter fullscreen mode Exit fullscreen mode

This function is a good first testing candidate because it's predictable: the same inputs always produce the same output.

Step 3: Write Your First Test File

Jest automatically finds files ending in .test.js (or inside a __tests__ folder). Create sum.test.js in the same directory:

// sum.test.js
const sum = require('./sum');

describe('sum function', () => {
  test('adds 1 + 2 to equal 3', () => {
    expect(sum(1, 2)).toBe(3);
  });
});
Enter fullscreen mode Exit fullscreen mode

What's happening here:

  • describe groups related tests together
  • test (or its alias it) defines a single test case
  • expect wraps the value you want to check
  • toBe is a matcher that checks strict equality

Step 4: Run the Test

Run your test suite:

npx jest
Enter fullscreen mode Exit fullscreen mode

or, using the script you added:

npm test
Enter fullscreen mode Exit fullscreen mode

You should see output similar to:

 PASS  ./sum.test.js
  sum function
    ✓ adds 1 + 2 to equal 3 (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Enter fullscreen mode Exit fullscreen mode

This tells you the test file ran, how many tests passed or failed, and how long execution took.

Step 5: Test for Failures Too

A good test suite doesn't just check that things work it checks that things break in expected ways. Add another test:

test('does not equal 4 when adding 1 + 2', () => {
  expect(sum(1, 2)).not.toBe(4);
});
Enter fullscreen mode Exit fullscreen mode

Try intentionally breaking your function to see a failing test in action:

function sum(a, b) {
  return a - b; // bug introduced
}
Enter fullscreen mode Exit fullscreen mode

Run Jest again, and you'll see a red FAIL result with details about what was expected versus what was received. This is exactly why unit tests matter they catch bugs like this before they reach production.

Common Jest Matchers Cheat Sheet

Matcher Use Case
toBe(value) Strict equality (primitives)
toEqual(value) Deep equality (objects/arrays)
toContain(item) Checks array/string contains an item
toThrow() Checks a function throws an error
toBeNull() Checks value is null
toBeTruthy() / toBeFalsy() Checks truthy/falsy value
toHaveLength(n) Checks array/string length

Bonus: Code Coverage

Jest can report how much of your code is actually exercised by tests:

npx jest --coverage
Enter fullscreen mode Exit fullscreen mode

This generates a summary table showing percentage coverage for statements, branches, functions, and lines plus a detailed HTML report in a coverage/ folder you can open in a browser.

Common Beginner Mistakes

  • Testing implementation instead of behavior - test what a function returns, not how it's written internally.
  • Not isolating tests - each test should be independent and not rely on the state left by another test.
  • Forgetting async/await in async tests - if you're testing a promise-based function, always await it or return the promise, or Jest may report a false pass.
  • Overly broad test names - vague names like test('it works') make failures hard to diagnose later.

FAQ

What is the difference between Jest and Mocha?
Jest bundles a test runner, assertion library, and mocking tools in one package, while Mocha is only a test runner and requires separate libraries like Chai (assertions) and Sinon (mocking).

Do I need Babel to use Jest with Node.js?
No. For standard CommonJS Node.js code, Jest works without Babel. You only need Babel if you're using ES modules (import/export) or JSX/TypeScript syntax that Node doesn't natively support.

Can Jest test async functions?
Yes. Jest supports async/await directly in test functions, as well as returning promises or using the done callback for callback-based code.

Is Jest good for TypeScript projects?
Yes. With ts-jest or Babel's TypeScript preset, Jest works well with TypeScript projects and can type-check alongside testing.

Do I need to install a separate assertion library with Jest?
No. Jest includes its own expect API with matchers like toBe, toEqual, and toContain, so no additional assertion library is required.

Conclusion

You've now set up Jest, written a testable function, created your first test file, and learned how to read both passing and failing test output. From here, the natural next steps are learning how to mock dependencies, test asynchronous code, and write integration tests that check how multiple functions work together.

Unit testing might feel like extra work at first, but it pays off fast - catching bugs early, documenting expected behavior, and giving you the confidence to refactor code without fear.

Want to go beyond the basics? Read our complete Jest Testing Guide for Node.js Developers: From Beginner to Advanced to learn about mocking, snapshot testing, asynchronous testing, code coverage, and advanced testing techniques.

Next up: Try writing tests for a function that involves async logic, like an API call or a database query - that's where Jest's mocking tools really start to shine.

Top comments (0)