π§ͺ Introduction to JavaScript Testing
Testing ensures your code works as expected, prevents bugs, and boosts confidence when refactoring or adding new features.
π Why Test Your Code?
- Detect bugs early
- Ensure consistent behavior
- Enable safe refactoring
- Document expected functionality
π Types of Tests
- Unit Tests: Test individual functions or modules
- Integration Tests: Check how modules work together
- End-to-End Tests: Simulate real user interaction (e.g., clicking buttons)
βοΈ Writing a Simple Unit Test
Letβs test a basic function:
// math.js
function add(a, b) {
return a + b;
}
// test
const result = add(2, 3);
console.assert(result === 5, 'Expected 2 + 3 to equal 5');
This test will only log an error if it fails. You can run it directly in the browser or Node.js console.
π§° Testing Frameworks
- Jest β Great for unit and integration testing
- Mocha + Chai β Flexible and powerful
- Vitest β Fast Jest-compatible runner (used with Vite)
- Cypress β End-to-end testing for UIs
π File Structure Example
project/
βββ src/
β βββ math.js
βββ tests/
β βββ math.test.js
π‘ Tip: Start testing small helper functions, then expand to larger components as you gain confidence.