Test in Practice

  • Practical testing covers writing test cases, running and debugging tests, and measuring test coverage for better code quality.
  • What is a Test Case?

    A test case is a small piece of code that checks whether a specific function or feature behaves as expected.

    Each test case usually includes:

    • Input

    • Expected output

    • Assertion to compare both

    Basic Structure of a Jest Test

test("description of the test", () => {
  // arrange
  // act
  // assert
});
  • Example – Simple Function Test

function multiply(a, b) {
  return a * b;
}

test("multiplies two numbers correctly", () => {
  const result = multiply(4, 5);
  expect(result).toBe(20);
});
  • Key Assertion Methods
    • toBe() – Exact match

    • toEqual() – Object/array comparison

    • toBeDefined() – Checks existence

    • toBeTruthy() – Truthy values

    Good Test Case Characteristics

    • Focused on one behavior

    • Easy to read

    • Independent from other tests

    • Predictable result


    Running & Debugging Tests

    Running Jest Tests

    Install Jest

npm install --save-dev jest
  • Add Test Script

"scripts": {
  "test": "jest"
}
  • Run Tests

npm test
  • Jest Output Meaning
    • ✅ Green – Test passed

    • ❌ Red – Test failed

    • Shows error message & line number


    Debugging a Failing Test

test("debug example", () => {
  console.log("Debugging value:", someValue);
  expect(someValue).toBe(10);
});
  • Helpful Jest Commands

    • jest --watch → Run tests automatically on changes

    • jest --runInBand → Run tests sequentially

    • jest --verbose → Detailed output


    Debugging Flow

Failing Test
   ↓
Read Error Message
   ↓
Inspect Code
   ↓
Fix Logic
   ↓
Re-run Test
  • Test Coverage Basics

    What is Test Coverage?

    Test coverage measures how much of your code is executed during testing.

    It helps identify:

    • Untested logic

    • Dead code

    • Risky areas

    Coverage Metrics 

    • Statements – Lines executed

    • Branches – if/else conditions

    • Functions – Called functions

    • Lines – Total code lines covered

    Generate Coverage Report

npm test -- --coverage
  • Coverage Report Example

File        | % Stmts | % Branch | % Funcs | % Lines
-----------------------------------------------
users.js    |   90%   |   80%    |   100%  |   90%
  • Why Coverage is Useful
    • Improves code reliability

    • Prevents missing edge cases

    • Required in professional projects

    Coverage Best Practices

    • Aim for meaningful coverage, not 100% blindly

    • Focus on business logic

    • Test edge cases

    • Combine with integration tests