Testing JavaScript with Jest
Learn to write reliable tests with Jest testing framework.
Why Testing Matters
Tests catch bugs early and provide confidence when refactoring. Investment in testing saves debugging time later.
Getting Started
npm install --save-dev jest
# In package.json
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
}
Basic Tests
// math.js
function add(a, b) { return a + b; }
module.exports = { add };
// math.test.js
const { add } = require('./math');
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
describe('add function', () => {
it('handles negative numbers', () => {
expect(add(-1, -2)).toBe(-3);
});
});
Mocking
const fetchData = jest.fn().mockResolvedValue({ data: 'test' });
test('fetches data', async () => {
const result = await fetchData();
expect(result.data).toBe('test');
expect(fetchData).toHaveBeenCalled();
});
Conclusion
Start with simple unit tests and expand coverage gradually. Even 50% coverage is better than none.