Setting Up Jest Testing in Your Node.js Application: A Complete Guide

gentritbiba

Gentrit Biba

Posted on November 8, 2024

Setting Up Jest Testing in Your Node.js Application: A Complete Guide

Jest is a popular testing framework maintained by Facebook that makes it easy to write and run tests for JavaScript applications. This guide will walk you through setting up Jest in your Node.js project from scratch.

Prerequisites

  • Node.js installed on your system
  • An existing Node.js project or a new one

Step 1: Initialize Your Project

If you don't have an existing project, create a new directory and initialize it:

mkdir my-node-project
cd my-node-project
npm init -y
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Jest

Install Jest as a development dependency:

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

Step 3: Configure Jest in package.json

Update your package.json to add Jest configuration and test script:

{
  "scripts": {
    "test": "jest",
    "test:watch": "jest --watch"
  },
  "jest": {
    "testEnvironment": "node",
    "coveragePathIgnorePatterns": [
      "/node_modules/"
    ],
    "moduleFileExtensions": ["js", "json"],
    "testMatch": ["**/__tests__/**/*.js", "**/?(*.)+(spec|test).js"],
    "verbose": true
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Create a Sample Function to Test

Create a new file called math.js:

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

function multiply(a, b) {
  return a * b;
}

module.exports = {
  sum,
  multiply
};
Enter fullscreen mode Exit fullscreen mode

Step 5: Write Your First Test

Create a test file called math.test.js:

// math.test.js
const { sum, multiply } = require('./math');

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

  test('multiplies 3 * 4 to equal 12', () => {
    expect(multiply(3, 4)).toBe(12);
  });
});
Enter fullscreen mode Exit fullscreen mode

Step 6: Additional Jest Configuration (Optional)

Create a jest.config.js file for more detailed configuration:

// jest.config.js
module.exports = {
  // Automatically clear mock calls and instances between every test
  clearMocks: true,

  // Indicates whether the coverage information should be collected while executing the test
  collectCoverage: true,

  // The directory where Jest should output its coverage files
  coverageDirectory: "coverage",

  // An array of regexp pattern strings used to skip coverage collection
  coveragePathIgnorePatterns: [
    "/node_modules/"
  ],

  // The test environment that will be used for testing
  testEnvironment: "node",

  // The glob patterns Jest uses to detect test files
  testMatch: [
    "**/__tests__/**/*.[jt]s?(x)",
    "**/?(*.)+(spec|test).[tj]s?(x)"
  ]
};
Enter fullscreen mode Exit fullscreen mode

Step 7: Running Tests

You can now run your tests using npm:

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage report
npm test -- --coverage
Enter fullscreen mode Exit fullscreen mode

Common Jest Matchers

Here are some commonly used Jest matchers:

// Exact equality
expect(value).toBe(2);

// Object matching
expect(data).toEqual({id: 1});

// Truthiness
expect(value).toBeTruthy();
expect(value).toBeFalsy();

// Numbers
expect(value).toBeGreaterThan(3);
expect(value).toBeLessThan(5);

// Strings
expect(string).toMatch(/pattern/);

// Arrays
expect(array).toContain(item);

// Exceptions
expect(() => {
  throw new Error('Wrong!');
}).toThrow('Wrong!');
Enter fullscreen mode Exit fullscreen mode

Testing Asynchronous Code

Jest handles async code testing gracefully:

// Testing Promises
test('async test', () => {
  return fetchData().then(data => {
    expect(data).toBe('data');
  });
});

// Using async/await
test('async test with async/await', async () => {
  const data = await fetchData();
  expect(data).toBe('data');
});
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. File Organization: Keep test files close to the code they're testing
   src/
     ├── math.js
     └── __tests__/
         └── math.test.js
Enter fullscreen mode Exit fullscreen mode
  1. Test Isolation: Each test should be independent and not rely on other tests

  2. Meaningful Descriptions: Use clear test descriptions

   describe('User authentication', () => {
     test('should successfully log in with valid credentials', () => {
       // test code
     });
   });
Enter fullscreen mode Exit fullscreen mode
  1. Setup and Teardown: Use Jest's lifecycle methods when needed
   beforeAll(() => {
     // Setup before all tests
   });

   afterEach(() => {
     // Cleanup after each test
   });
Enter fullscreen mode Exit fullscreen mode

Conclusion

You now have a fully configured Jest testing environment in your Node.js application. Remember to:

  • Write tests as you develop new features
  • Aim for high test coverage
  • Run tests frequently
  • Keep tests maintainable and readable

Your tests will help catch bugs early, serve as documentation, and make refactoring easier.

This was fun! I write about stuff like this all the time on my blog. Swing by if you're into coding, math puzzles, and that kind of thing: blog.gentrit.dev

💖 💪 🙅 🚩
gentritbiba
Gentrit Biba

Posted on November 8, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related