⚡
Testing JavaScript Code
Advanced
140 XP
60 min
Lesson Content
Testing JavaScript Code
Testing ensures your code works correctly and prevents bugs. Learn to write effective tests for JavaScript applications.
Unit Testing
// Simple test function
function test(description, fn) {
try {
fn();
console.log('✓', description);
} catch (error) {
console.log('✗', description);
console.error(error);
}
}
function expect(actual) {
return {
toBe: (expected) => {
if (actual !== expected) {
throw new Error(`Expected ${expected}, got ${actual}`);
}
}
};
}Test Structure
// Arrange - Set up test data
// Act - Execute code
// Assert - Verify resultsTesting Async Code
async function testAsync() {
const result = await asyncFunction();
expect(result).toBe(expected);
}Example Code
Write tests for JavaScript functions
// Simple test framework
function test(description, fn) {
try {
fn();
console.log('✓', description);
} catch (error) {
console.log('✗', description);
console.error(error.message);
}
}
function expect(actual) {
return {
toBe: (expected) => {
if (actual !== expected) {
throw new Error(`Expected ${expected}, got ${actual}`);
}
},
toEqual: (expected) => {
if (JSON.stringify(actual) !== JSON.stringify(expected)) {
throw new Error(`Expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
}
}
};
}
// Function to test
function add(a, b) {
return a + b;
}
// Tests
test('adds 2 + 3 to equal 5', () => {
expect(add(2, 3)).toBe(5);
});
test('adds negative numbers', () => {
expect(add(-1, -2)).toBe(-3);
});Expected Output:
✓ adds 2 + 3 to equal 5 ✓ adds negative numbers
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code