Member-only story

Mastering Jest: Day 2 — Writing Basic Tests

Introduction

Skyz Walker
3 min readJul 19, 2024
Code
Photo by Krishna Pandey on Unsplash

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Skyz Walker
Skyz Walker

Written by Skyz Walker

I am a passionate and dedicated Web & CloudEng with a strong focus on both frontend and backend technologies. I specialize in creating stylish, modern websites.

No responses yet

Write a response