SmartCodingTips

πŸ§ͺ 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.