Testing with Jest

2026-01-1013 min read
JestTestingJavaScript
Share:
Testing with Jest

Why Testing Matters

Testing ensures your code works as expected and prevents regressions. Jest is a zero-configuration testing framework with built-in mocking and assertion libraries.

Setting Up Jest

Install Jest:

npm install --save-dev jest

Add to package.json:

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

Writing Your First Test

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

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

Matchers

Jest provides various matchers:

  • expect(value).toBe(expected) - Strict equality
  • expect(value).toEqual(expected) - Deep equality
  • expect(value).toBeTruthy() - Truthy values
  • expect(array).toContain(item) - Array containment

Testing Asynchronous Code

Use async/await or Promises:

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

Mocking

Mock functions and modules to isolate tests:

const mockFn = jest.fn();
  mockFn.mockReturnValue('mocked value');
  expect(mockFn()).toBe('mocked value');

Mocking Modules

jest.mock('./api');
  const api = require('./api');
  api.fetchUser.mockResolvedValue({ name: 'John' });

Best Practices

  • Test behavior, not implementation
  • Use descriptive test names
  • Arrange-Act-Assert pattern
  • Test edge cases and error conditions
  • Keep tests fast and independent

Jest's simplicity and features make it an excellent choice for testing JavaScript applications, ensuring code reliability and maintainability.

About the Author

Anna Thompson

Anna Thompson

Quality assurance specialist and testing advocate promoting reliable, maintainable code.

Related Posts