Day 01 Foundations

Day 1

Day 1

~1 hour Intermediate Hands-on Precision AI Academy

Today's Objective

By the end of this lesson you will understand unit testing with jest deeply enough to apply it immediately in real projects.

bash.txt
BASH
npm install --save-dev jest
# or for TypeScript:
npm install --save-dev jest @types/jest ts-jest
javascript.txt
JAVASCRIPT
// src/utils/math.js
export function add(a, b) { return a + b; }
export function divide(a, b) {
  if (b === 0) throw new Error('Division by zero');
  return a / b;
}

// src/utils/math.test.js
import { add, divide } from './math';

describe('math utils', () => {
  test('adds two numbers', () => {
    expect(add(2, 3)).toBe(5);
  });

  test('divides two numbers', () => {
    expect(divide(10, 2)).toBe(5);
    expect(divide(10, 2)).toBeCloseTo(5);
  });

  test('throws on divide by zero', () => {
    expect(() => divide(10, 0)).toThrow('Division by zero');
  });
});
javascript.txt
JAVASCRIPT
// Mocking modules
import * as api from './api';

jest.mock('./api');

test('calls the API once', async () => {
  api.fetchUser.mockResolvedValue({ id: 1, name: 'Bo' });

  const user = await api.fetchUser(1);

  expect(api.fetchUser).toHaveBeenCalledTimes(1);
  expect(api.fetchUser).toHaveBeenCalledWith(1);
  expect(user.name).toBe('Bo');
});

Exercise: Write 10 Unit Tests

  1. Create a string utils module (capitalize, truncate, slugify)
  2. Write one test for each function
  3. Add an edge case test (empty string, null input)
  4. Run jest --watch and fix failures in real time
  5. Check coverage with jest --coverage

Day 1 Summary