</>
Skip to content
Node.js lessons (42/44)

Node.js — Testing

Jest

npm install -D jest

Basic Test

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

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

Test Suite

describe('Calculator', () => {
    test('adds numbers', () => {
        expect(add(1, 2)).toBe(3);
    });
    
    test('subtracts numbers', () => {
        expect(subtract(5, 3)).toBe(2);
    });
});

Matchers

MatcherDescription
toBeStrict equality
toEqualDeep equality
toBeTruthyIs truthy
toContainArray contains
toThrowThrows error
toBeNullIs null

Async Tests

test('fetches data', async () => {
    const data = await fetchData();
    expect(data).toBeDefined();
});

Mocking

jest.mock('./database');

test('calls database', async () => {
    const mockFn = jest.fn().mockResolvedValue({ id: 1 });
    const result = await mockFn();
    expect(result).toEqual({ id: 1 });
});

Run Tests

npm test
npx jest --coverage
npx jest --watch

Mini Practice

  1. Write basic tests
  2. Create test suites
  3. Use different matchers
  4. Mock functions

Up Next

Continue with Security — security best practices.

Related Topics

Frequently Asked Questions about Testing

What is Testing in Node.js?

Testing is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Testing?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Testing.

Why is Testing important in Node.js?

Testing is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.