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 equalityexpect(value).toEqual(expected)- Deep equalityexpect(value).toBeTruthy()- Truthy valuesexpect(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
Quality assurance specialist and testing advocate promoting reliable, maintainable code.
Related Posts
Getting Started with React
React is a popular JavaScript library for building user interfaces. Learn the basics including components, props, state, and setting up your first project.
Understanding TypeScript
TypeScript enhances JavaScript with static typing. Discover how it improves code quality, tooling, and developer experience.