# 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:

```plaintext
mkdir jest-first-test
cd jest-first-test
npm init -y
```

Install Jest as a dev dependency:

```plaintext
npm install --save-dev jest
```

Open `package.json` and add a test script:

```plaintext
{
  "scripts": {
    "test": "jest"
  }
}
```

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`:

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

module.exports = sum;
```

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:

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

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

**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:

```plaintext
npx jest
```

or, using the script you added:

```plaintext
npm test
```

You should see output similar to:

```plaintext
 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
```

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:

```plaintext
test('does not equal 4 when adding 1 + 2', () => {
  expect(sum(1, 2)).not.toBe(4);
});
```

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

```plaintext
function sum(a, b) {
  return a - b; // bug introduced
}
```

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:

```plaintext
npx jest --coverage
```

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.
    

## **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 c[omplete Jest Testing Guide for Node.js Developers: From Beginner to Advanced](https://www.synfinitydynamics.com/blogs/jest-testing-guide-nodejs?utm_source=hashnode&utm_medium=article&utm_campaign=blog_distribution) to learn about mocking, snapshot testing, asynchronous testing, code coverage, and advanced testing techniques.
