Testing Return Values
The most straightforward thing you can test is what a function returns. You give it some input, you check the output. This is where most people start, and there is a good reason for that.
Trust me, once you get comfortable testing return values, everything else in testing will make way more sense.
Simple Function Tests
Start with functions that take inputs and return outputs. No side effects, no mutations, just pure functions.
function multiply(a, b) {
return a * b;
}
describe('multiply', () => {
it('multiplies two positive numbers', () => {
expect(multiply(3, 4)).toBe(12);
});
it('handles zero', () => {
expect(multiply(5, 0)).toBe(0);
});
it('handles negative numbers', () => {
expect(multiply(-2, 3)).toBe(-6);
});
});
See how each test checks one specific case? That is the key. One test, one behavior. Keep them focused.
Testing Strings and Formatting
String functions are great for testing because the output is easy to verify.
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
describe('capitalize', () => {
it('capitalizes the first letter', () => {
expect(capitalize('hello')).toBe('Hello');
});
it('handles empty string', () => {
expect(capitalize('')).toBe('');
});
it('handles single character', () => {
expect(capitalize('a')).toBe('A');
});
});
Multiple Assertions in One Test
Sometimes you want to check multiple things about the same result. That is fine, as long as they all relate to the same behavior.
function getUser(id) {
return {
id: id,
name: 'Alice',
email: `user${id}@example.com`
};
}
it('returns correct user object', () => {
const user = getUser(1);
expect(user.id).toBe(1);
expect(user.name).toBe('Alice');
expect(user.email).toBe('user1@example.com');
});
Those three assertions all test the same thing: that getUser returns the right data. If any of them fail, you know exactly what went wrong.
Try it Yourself →Key Takeaways
- Test one behavior per test case to keep things clear
- Start with pure functions that take input and return output
- Test edge cases like empty strings, zero, and negative numbers
- Multiple assertions are fine if they test the same behavior