Member-only story
Mastering Jest: Day 2 — Writing Basic Tests
Introduction
Welcome back to our journey of mastering Jest! Yesterday, we covered the basics of Jest, including installation and writing our first test. Today, we’ll dive deeper into writing and structuring basic test cases. Understanding how to write effective tests is crucial for maintaining code quality and ensuring that your application behaves as expected.
Testing Functions
Testing functions is the cornerstone of any testing strategy. Let’s start by writing tests for simple functions. We’ll use the same sum
function from yesterday and add more test cases to cover different scenarios.
// sum.js
function sum(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new Error('Arguments must be numbers');
}
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);
});
test('adds -1 + -1 to equal -2', () => {
expect(sum(-1, -1)).toBe(-2);
});
test('throws error when arguments are not numbers', () => {
expect(() => sum(1, 'a')).toThrow('Arguments must be numbers');
});
In these tests, we use Jest’s expect
function and various matchers like toBe
and toThrow
to assert different outcomes.