Testing Real Functions
Enough with the toy examples. Let us test something real. In this lesson, we will test validation, formatting, and calculation functions that you would actually use in a real project.
One thing that helped me was writing tests for functions I had already built. It showed me which ones were easy to test and which ones needed refactoring.
Testing Validation
Validation functions are perfect for unit testing. They take input and return true or false.
function validateEmail(email) {
if (!email) return false;
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
describe('validateEmail', () => {
it('returns true for valid email', () => {
expect(validateEmail('alice@example.com')).toBe(true);
});
it('returns false for missing @', () => {
expect(validateEmail('aliceexample.com')).toBe(false);
});
it('returns false for empty string', () => {
expect(validateEmail('')).toBe(false);
});
it('returns false for null', () => {
expect(validateEmail(null)).toBe(false);
});
});
Testing Formatting Functions
Formatting functions transform data. Test that the output matches what you expect.
function formatCurrency(amount) {
return `$${amount.toFixed(2)}`;
}
describe('formatCurrency', () => {
it('formats whole number', () => {
expect(formatCurrency(10)).toBe('$10.00');
});
it('formats decimal', () => {
expect(formatCurrency(9.99)).toBe('$9.99');
});
it('formats zero', () => {
expect(formatCurrency(0)).toBe('$0.00');
});
});
Testing Calculations
Math functions need tests for edge cases like zero, negative numbers, and large values.
function calculateTip(bill, tipPercent) {
if (bill < 0) throw new Error('Bill cannot be negative');
return bill * (tipPercent / 100);
}
describe('calculateTip', () => {
it('calculates 20% tip', () => {
expect(calculateTip(50, 20)).toBe(10);
});
it('calculates 0% tip', () => {
expect(calculateTip(50, 0)).toBe(0);
});
it('throws for negative bill', () => {
expect(() => calculateTip(-10, 20)).toThrow('Bill cannot be negative');
});
});
Try it Yourself →
Key Takeaways
- Validation functions are great candidates for unit tests
- Test formatting functions with expected output strings
- Always test edge cases like zero, negative, and null values
- Test error paths for functions that can throw
- Real-world tests are just small focused tests on practical functions