SyntaxPilot
Courses/Vibe Coding/Lesson 27
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Vibe Coding · Lesson 27 of 40

Testing AI code

unit testtest runner (Jest/pytest)asking the AI for testsedge casesa test that catches a real AI bugmanual test checklistwhy green tests can still miss bugs

Vibe Coding: build real apps with AI · Episode 27. Every agent run below is real: Claude Code 2.1.322 (model claude-opus-5-5) in print mode (claude -p --permission-mode acceptEdits), on 12 November 2026, in /home/asha/projects/trip-split (a Git repository). In this mode the agent may write files but needs approval to run commands, and nobody approved, so it never ran a single one of its own tests. We ran them all; every output below is real.

Tools used: Jest 30.5.2 (the latest on npm on 12 November 2026), pytest 9.1.1, Node.js v22, Python 3. Names and amounts are made up for this video.

Sources (read on 12 November 2026): Jest docs, Using Matchers (version 30.5); pytest docs, Get Started.

The problem: a paisa vanished

Asha, Ravi and Neha went to Goa. Asha built a split app with AI and tried it once: ₹1,000 among 4 = ₹250 each. "It works!" Then a ₹100 auto ride among 3: ₹33.33 each, and 33.33 × 3 = 99.99. One paisa vanished. Over a hundred bills, the totals never match.

The obvious way: try it once by hand (run in the compiler)

// Asha's first version, checked once by hand
function splitBill(total, people) {
  const share = Number((total / people).toFixed(2));
  return Array(people).fill(share);
}

console.log(splitBill(1000, 4)); // she tried this one: looks fine

const shares = splitBill(100, 3);
console.log(shares);
console.log("sum:", shares.reduce((a, b) => a + b, 0));

Output:

[ 250, 250, 250, 250 ]
[ 33.33, 33.33, 33.33 ]
sum: 99.99

toFixed(2) rounds a number to 2 decimals (and returns text, which Number(...) turns back into a number).

Why it fails

  • One case, and the easy one (1000 divides by 4 exactly).
  • Checked by eye, once.
  • Every AI change can break it again, and nobody re-checks by hand.

We need checks that are written down once and run themselves every time.

Inventing a unit test (run in the compiler)

function splitBill(total, people) {
  const share = Number((total / people).toFixed(2));
  return Array(people).fill(share);
}

// A tiny test: run the code, compare with the answer you KNOW is right
function check(name, actual, expected) {
  const ok = JSON.stringify(actual) === JSON.stringify(expected);
  console.log(ok ? "PASS" : "FAIL", name);
  if (!ok) console.log("   got", JSON.stringify(actual), "expected", JSON.stringify(expected));
}

const paise = (shares) => shares.reduce((sum, s) => sum + Math.round(s * 100), 0);

check("1000 among 4", splitBill(1000, 4), [250, 250, 250, 250]);
check("100 among 3 adds up", paise(splitBill(100, 3)), 10000);
check("1 rupee among 3 adds up", paise(splitBill(1, 3)), 100);

Output:

PASS 1000 among 4
FAIL 100 among 3 adds up
   got 9999 expected 10000
FAIL 1 rupee among 3 adds up
   got 99 expected 100

That check function is a unit test: a small piece of code that runs one part (a "unit", usually one function) of your program with a known right answer and says pass or fail. (JSON.stringify turns a value into text, so two arrays can be compared.)

Real-life example: the OMR answer sheet

In an exam In testing
Answer key: "Q7: option B" A test + its assertion (a statement that must be true: for this input, this answer)
The OMR machine marks 1,000 sheets fast A test runner: finds all tests, runs them, reports (Jest for JavaScript, pytest for Python)
The whole question paper A test suite: all your tests together
Questions not on the key are never checked Untested cases: bugs hide here. Green ≠ bug-free

Prompt 1 (real): splitBill, with tests

claude -p "Create split.js with a function splitBill(total, people) for our trip expense app. total is the bill in rupees, like 1000 or 999.99. people is how many friends share it. Return an array with each person's share in rupees. The shares must add up to exactly the total. Export it so other files can use it." --permission-mode acceptEdits

It wrote split.js and, on its own, split.test.js (6 tests). Its reply: "I haven't run the tests: running npx jest needed your approval and didn't go through. Run npm test to check them." It also warned: "if other code adds the rupee values with plain +, JavaScript decimals can give a result like 999.9999999999999 instead of 1000." Remember that warning.

The AI's split.js (complete):

/**
 * Split a bill evenly between people, to the paisa.
 *
 * The math is done in whole paise (integers) so floating-point rounding can't
 * lose or invent money. Any paise that don't divide evenly are given, one
 * each, to the first people in the list, so the shares always add up to the
 * total.
 *
 *   splitBill(1000, 3)   // [333.34, 333.33, 333.33]
 *   splitBill(999.99, 2) // [500, 499.99]
 *
 * @param {number} total  Bill amount in rupees, at most 2 decimal places.
 * @param {number} people Number of people sharing it (positive integer).
 * @returns {number[]} Each person's share in rupees.
 */
function splitBill(total, people) {
  if (typeof total !== 'number' || !Number.isFinite(total) || total < 0) {
    throw new TypeError('total must be a non-negative number of rupees');
  }
  if (!Number.isInteger(people) || people < 1) {
    throw new TypeError('people must be a positive whole number');
  }

  const totalPaise = Math.round(total * 100);
  if (Math.abs(totalPaise - total * 100) > 1e-6) {
    throw new RangeError('total cannot have more than 2 decimal places');
  }

  const base = Math.floor(totalPaise / people);
  const extra = totalPaise % people; // this many people pay 1 paisa more

  const shares = [];
  for (let i = 0; i < people; i++) {
    shares.push((base + (i < extra ? 1 : 0)) / 100);
  }
  return shares;
}

module.exports = { splitBill };

The idea: money in whole paise (1 rupee = 100 paise), so all the maths uses whole numbers. Leftover paise go one each to the first people: ₹100 among 3 → 33.34, 33.33, 33.33, which adds up to exactly 100.

The AI's tests (complete split.test.js):

const { splitBill } = require('./split');

// Sum in paise so the check itself isn't fooled by float addition.
const sumPaise = (shares) => shares.reduce((s, x) => s + Math.round(x * 100), 0);

describe('splitBill', () => {
  test('even split', () => {
    expect(splitBill(1000, 4)).toEqual([250, 250, 250, 250]);
  });

  test('uneven split gives leftover paise to the first people', () => {
    expect(splitBill(1000, 3)).toEqual([333.34, 333.33, 333.33]);
    expect(splitBill(999.99, 2)).toEqual([500, 499.99]);
    expect(splitBill(0.05, 3)).toEqual([0.02, 0.02, 0.01]);
  });

  test('one person pays everything', () => {
    expect(splitBill(999.99, 1)).toEqual([999.99]);
  });

  test('more people than paise', () => {
    expect(splitBill(0.02, 3)).toEqual([0.01, 0.01, 0]);
  });

  test('shares always add up to the total', () => {
    for (const total of [1000, 999.99, 0.01, 1234.56, 100.1, 0.3, 76543.21]) {
      for (let people = 1; people <= 13; people++) {
        const shares = splitBill(total, people);
        expect(shares).toHaveLength(people);
        expect(sumPaise(shares)).toBe(Math.round(total * 100));
        expect(Math.max(...shares) - Math.min(...shares)).toBeLessThanOrEqual(0.0100001);
      }
    }
  });

  test('rejects bad input', () => {
    expect(() => splitBill(100, 0)).toThrow();
    expect(() => splitBill(100, 2.5)).toThrow();
    expect(() => splitBill(-5, 2)).toThrow();
    expect(() => splitBill('100', 2)).toThrow();
    expect(() => splitBill(NaN, 2)).toThrow();
    expect(() => splitBill(10.005, 2)).toThrow();
  });
});

How to read a Jest test: describe groups related tests; test('name', fn) is one test; expect(value).toEqual(right) is the assertion; expect(() => ...).toThrow() checks that bad input causes an error instead of a strange answer. toBe vs toEqual: the Jest docs say "toBe uses Object.is to test exact equality. If you want to check the value of an object, use toEqual" (arrays and objects need toEqual).

Run them yourself

package.json has "scripts": { "test": "jest" }, so npm test runs Jest, which finds files ending in .test.js:

$ npm test

> trip-split@1.0.0 test
> jest

Test Suites: 1 passed, 1 total
Tests:       6 passed, 6 total
Snapshots:   0 total
Time:        0.316 s
Ran all test suites.

Prompt 2 (real): settle up, with tests

claude -p "Now add settle.js with a function settleUp(expenses). Each expense looks like { paidBy: 'Asha', amount: 1200, sharedBy: ['Asha', 'Ravi', 'Neha'] }: one person paid, and the amount is shared equally by the people in sharedBy. Return the list of payments that settles everyone, like [{ from: 'Ravi', to: 'Asha', amount: 400 }], with as few payments as possible. Also write Jest tests for it." --permission-mode acceptEdits

It wrote a 146-line settle.js with an exact search over every way to split people into groups ("guaranteed only for up to 20 people"), and a 168-line test file with 10 tests, including 300 random trips checked against a brute-force search. Its reply: "I added settle.js and settle.test.js, but I haven't run the tests. Each attempt to run npm test was blocked waiting for your approval, so I don't know yet whether they pass." (For three friends, that's a lot of code to trust: the more code, the more you need tests you have actually run.)

Reading a failing test (real)

$ npm test
FAIL ./settle.test.js
  ● settleUp › uneven splits settle to the paisa

    expect(received).toBe(expected) // Object.is equality

    Expected: 28333.999999999996
    Received: 28334

      103 |     const payments = settleUp(expenses);
      104 |     expectSettles(expenses, payments);
    > 105 |     for (const p of payments) expect(paise(p.amount)).toBe(p.amount * 100);
          |                                                       ^
      106 |   });

Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 failed, 15 passed, 16 total

Read it top to bottom: the test's name, the matcher (toBe, exact equality), Expected vs Received, and the line (105). Then the question every failing test asks: is the bug in the code, or in the test?

Check the answer by hand

The test's trip: Asha paid ₹1,000 for Asha, Ravi, Neha; Neha paid ₹99.99 for Ravi and Neha; Ravi paid ₹0.05 for all three.

Person Paid Share of 1000 Share of 99.99 Share of 0.05 Balance
Asha 1000.00 333.34 – 0.02 +666.64 (is owed)
Ravi 0.05 333.33 50.00 0.02 −383.30 (owes)
Neha 99.99 333.33 49.99 0.01 −283.34 (owes)

settleUp returned:

[
  { from: 'Ravi', to: 'Asha', amount: 383.3 },
  { from: 'Neha', to: 'Asha', amount: 283.34 }
]

Exactly right. The code is fine.

The floating-point trap (run in the compiler)

console.log(283.34 * 100);
console.log(Math.round(283.34 * 100));
console.log(0.1 + 0.2);

Output:

28333.999999999996
28334
0.30000000000000004

Floating point is the way computers store decimal numbers, in binary (base 2). Most decimals can't be stored exactly, just as 1/3 can't be written exactly as a decimal, so tiny errors appear. Rounding to whole paise removes them.

The real AI mistake

Its own test multiplied a float by 100 and demanded exact equality: expect(paise(p.amount)).toBe(p.amount * 100). In prompt 1 the same AI warned us about exactly this kind of float error. And it never ran the test, so it never saw it fail. Lessons: always run AI tests yourself, and read a failure before "fixing": if Asha had said "make the tests pass", the AI might have changed correct code.

Prompt 3 (real): "Code or test? Fix only that."

claude -p "I ran npm test. 15 passed, 1 failed:

  ● settleUp › uneven splits settle to the paisa
    expect(received).toBe(expected) // Object.is equality
    Expected: 28333.999999999996
    Received: 28334
    > 105 |     for (const p of payments) expect(paise(p.amount)).toBe(p.amount * 100);

The payments themselves look right to me (Ravi pays Asha 383.3, Neha pays Asha 283.34). Is the bug in settle.js or in the test? Fix only that." --permission-mode acceptEdits

Reply: "The bug was in the test, so that's the only file I changed. settle.js is untouched." … "283.34 * 100 gives 28333.999999999996, so the check failed even though the payment was right." The fix:

-    for (const p of payments) expect(paise(p.amount)).toBe(p.amount * 100);
+    for (const p of payments) expect(paise(p.amount) / 100).toBe(p.amount);
$ npm test
Test Suites: 2 passed, 2 total
Tests:       16 passed, 16 total

Edge cases: green tests can still miss bugs

An edge case is an unusual input at the limits: 0, 1, a huge number, a negative, an empty list; awkward decimals (0.01, 99.99, 2399.40); messy text from forms ("Ravi ", "ravi", ""). The AI tests what it thought of; you add what you know about your users.

Our own test first (real)

Neha typed "Ravi " (with a space) into the form. Asha writes the test before asking for a fix:

const { settleUp } = require('./settle');

// Names come from a form, so people type extra spaces
test('"Ravi " and "Ravi" are the same person', () => {
  const payments = settleUp([
    { paidBy: 'Ravi', amount: 900, sharedBy: ['Asha', 'Ravi ', 'Neha'] },
  ]);
  expect(payments).toEqual([
    { from: 'Asha', to: 'Ravi', amount: 300 },
    { from: 'Neha', to: 'Ravi', amount: 300 },
  ]);
});
$ npx jest names
FAIL ./names.test.js
  ● "Ravi " and "Ravi" are the same person

    expect(received).toEqual(expected) // deep equality

    - Expected  - 0
    + Received  + 5

    @@ -4,9 +4,14 @@
          "from": "Asha",
          "to": "Ravi",
        },
        Object {
          "amount": 300,
    +     "from": "Ravi ",
    +     "to": "Ravi",
    +   },
    +   Object {
    +     "amount": 300,
          "from": "Neha",
          "to": "Ravi",
        },
      ]

Tests:       1 failed, 1 total

Ravi pays Ravi ₹300, while all 16 of the AI's tests were green. Writing the test first is test-driven development (TDD): describe what "right" looks like, then change the code until it passes.

Prompt 4 (real)

claude -p "I added names.test.js. It fails: settleUp treats 'Ravi ' (with a space, typed in a form) and 'Ravi' as two people, so Ravi pays Ravi 300. Make names match after trimming spaces at the start and end. Don't change anything else, and don't edit names.test.js." --permission-mode acceptEdits

"Don't edit the test" matters: otherwise an AI can make a test pass by weakening the test. The real diff:

-    const { paidBy, amount, sharedBy } = e;
+    const { amount } = e;
+    // Names come from a form, so ignore spaces at the start and end.
+    const trim = (n) => (typeof n === 'string' ? n.trim() : n);
+    const paidBy = trim(e.paidBy);
     if (typeof paidBy !== 'string' || paidBy === '') {
       throw new TypeError(`expense ${i}: paidBy must be a name`);
     }
-    if (!Array.isArray(sharedBy) || sharedBy.length === 0) {
+    if (!Array.isArray(e.sharedBy) || e.sharedBy.length === 0) {
       throw new TypeError(`expense ${i}: sharedBy must be a non-empty list of names`);
     }
+    const sharedBy = e.sharedBy.map(trim);
$ git diff --stat
 settle.js | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
$ npm test
Test Suites: 3 passed, 3 total
Tests:       17 passed, 17 total

pytest (real)

claude -p "Our Python backend needs the same thing. Write split_bill.py with split_bill(total, people) following the same rules as split.js, and pytest tests in test_split_bill.py." --permission-mode acceptEdits

The pytest docs: "pytest will run all files of the form test_.py or _test.py in the current directory and its subdirectories", it finds test_-prefixed functions, and "You can use the assert statement to verify test expectations."

$ python3 -m pytest -q
........................................................................ [ 65%]
......................................                                   [100%]
110 passed in 0.05s

Each dot is one passing test; 8 test functions became 110 tests because @pytest.mark.parametrize runs one function for many inputs. The AI's split_bill.py:

"""Split a bill evenly between people, to the paisa.

Python port of ``split.js``. The math is done in whole paise (integers) so
floating-point rounding can't lose or invent money. Any paise that don't
divide evenly are given, one each, to the first people in the list, so the
shares always add up to the total.

    >>> split_bill(1000, 3)
    [333.34, 333.33, 333.33]
    >>> split_bill(999.99, 2)
    [500.0, 499.99]
"""

from decimal import Decimal
from numbers import Real


def split_bill(total, people):
    """Return each person's share of ``total`` rupees, split ``people`` ways.

    :param total: Bill amount in rupees (int, float or Decimal), non-negative,
        at most 2 decimal places.
    :param people: Number of people sharing it (positive int).
    :returns: List of ``people`` shares in rupees, as floats. Earlier people
        pay at most 1 paisa more than later ones.
    :raises TypeError: if ``total`` isn't a number or ``people`` isn't an int.
    :raises ValueError: if ``total`` is negative, not finite, or has more than
        2 decimal places, or ``people`` is less than 1.
    """
    # bool is a subclass of int; True/False are never a sensible amount.
    if isinstance(total, bool) or not isinstance(total, (Real, Decimal)):
        raise TypeError("total must be a non-negative number of rupees")
    if isinstance(people, bool) or not isinstance(people, int):
        raise TypeError("people must be a positive whole number")

    # str() of a float is its shortest round-tripping form, so 100.1 becomes
    # Decimal("100.1") rather than 100.099999999999994315658...
    amount = total if isinstance(total, Decimal) else Decimal(str(total))
    if not amount.is_finite() or amount < 0:
        raise ValueError("total must be a non-negative number of rupees")
    if people < 1:
        raise ValueError("people must be a positive whole number")

    paise = amount * 100
    if paise != paise.to_integral_value():
        raise ValueError("total cannot have more than 2 decimal places")
    total_paise = int(paise)

    base, extra = divmod(total_paise, people)  # `extra` people pay 1 paisa more
    return [(base + (1 if i < extra else 0)) / 100 for i in range(people)]

Our own pytest fails too (real)

from split_bill import split_bill

def test_shares_add_up_hotel_bill():
    shares = split_bill(2399.40, 3)
    assert shares == [799.80, 799.80, 799.80]
    assert sum(shares) == 2399.40
$ python3 -m pytest -q test_ours.py
F                                                                        [100%]
=================================== FAILURES ===================================
________________________ test_shares_add_up_hotel_bill _________________________

    def test_shares_add_up_hotel_bill():
        shares = split_bill(2399.40, 3)
        assert shares == [799.80, 799.80, 799.80]
>       assert sum(shares) == 2399.40
E       assert 2399.3999999999996 == 2399.4
E        +  where 2399.3999999999996 = sum([799.8, 799.8, 799.8])

test_ours.py:6: AssertionError
=========================== short test summary info ============================
FAILED test_ours.py::test_shares_add_up_hotel_bill - assert 2399.399999999999...
1 failed in 0.01s

The shares were right (the first assert passed); our test made the same floating-point mistake as the AI's. The fix, adding money in whole paise:

from split_bill import split_bill

def test_shares_add_up_hotel_bill():
    shares = split_bill(2399.40, 3)
    assert shares == [799.80, 799.80, 799.80]
    # add money in whole paise, never as floats
    assert sum(round(s * 100) for s in shares) == 239940
$ python3 -m pytest -q test_ours.py
.                                                                        [100%]
1 passed in 0.00s

For decimals where a tiny difference is fine, Jest has toBeCloseTo ("For floating point equality, use toBeCloseTo instead of toEqual, because you don't want a test to depend on a tiny rounding error.") and pytest has pytest.approx (assert (0.1 + 0.2) == pytest.approx(0.3)). For money, whole paise is clearer.

The manual test checklist

Unit tests check functions; they don't look at your screen. Before you share the app:

  • [ ] Open the real page: does it look right?
  • [ ] Type real, messy input into every form.
  • [ ] Try it on a phone and on a slow connection.
  • [ ] Read the error messages: would a friend understand them?
  • [ ] Every bug you find by hand becomes a new test, so it never comes back.

The finished settle.js

const { splitBill } = require('./split');

// Above this many people with a non-zero balance, the exact search
// (2^n states) gets slow, so we fall back to a greedy plan instead.
const EXACT_LIMIT = 20;

/**
 * Work out who should pay whom so everyone ends up even.
 *
 *   settleUp([{ paidBy: 'Asha', amount: 1200, sharedBy: ['Asha', 'Ravi', 'Neha'] }])
 *   // [{ from: 'Ravi', to: 'Asha', amount: 400 }, { from: 'Neha', to: 'Asha', amount: 400 }]
 *
 * Each expense is split with splitBill, so the money is tracked in whole paise
 * and any leftover paise go to the first people in `sharedBy`.
 *
 * Fewest payments: a group of k people whose balances add up to zero can always
 * be settled with k - 1 payments, so the minimum is (people who owe or are owed)
 * minus (the most separate zero-sum groups they can be split into). We search
 * for that split exactly when at most EXACT_LIMIT people have a non-zero
 * balance. Beyond that the problem is too expensive to solve exactly, and a
 * greedy plan is used: still at most one payment fewer than the number of
 * people, but not always the minimum.
 *
 * @param {{ paidBy: string, amount: number, sharedBy: string[] }[]} expenses
 * @returns {{ from: string, to: string, amount: number }[]} Payments in rupees.
 */
function settleUp(expenses) {
  if (!Array.isArray(expenses)) {
    throw new TypeError('expenses must be an array');
  }

  // Net balance per person in paise: positive = is owed money, negative = owes.
  const balance = new Map();
  const add = (name, paise) => balance.set(name, (balance.get(name) || 0) + paise);

  expenses.forEach((e, i) => {
    if (!e || typeof e !== 'object') {
      throw new TypeError(`expense ${i} must be an object`);
    }
    const { amount } = e;
    // Names come from a form, so ignore spaces at the start and end.
    const trim = (n) => (typeof n === 'string' ? n.trim() : n);
    const paidBy = trim(e.paidBy);
    if (typeof paidBy !== 'string' || paidBy === '') {
      throw new TypeError(`expense ${i}: paidBy must be a name`);
    }
    if (!Array.isArray(e.sharedBy) || e.sharedBy.length === 0) {
      throw new TypeError(`expense ${i}: sharedBy must be a non-empty list of names`);
    }
    const sharedBy = e.sharedBy.map(trim);
    if (sharedBy.some((n) => typeof n !== 'string' || n === '')) {
      throw new TypeError(`expense ${i}: every name in sharedBy must be a non-empty string`);
    }
    if (new Set(sharedBy).size !== sharedBy.length) {
      throw new TypeError(`expense ${i}: sharedBy lists someone twice`);
    }

    const shares = splitBill(amount, sharedBy.length); // validates amount
    add(paidBy, Math.round(amount * 100));
    sharedBy.forEach((name, j) => add(name, -Math.round(shares[j] * 100)));
  });

  const people = [...balance].filter(([, b]) => b !== 0);
  const groups =
    people.length <= EXACT_LIMIT ? zeroSumGroups(people) : [people];

  const payments = [];
  for (const group of groups) payments.push(...settleGroup(group));
  return payments;
}

/**
 * Split [name, balance] pairs into as many separate zero-sum groups as possible.
 *
 * dp[mask] = most zero-sum groups that the people in `mask` can be arranged
 * into, if we add them one at a time and close a group whenever the running
 * total hits zero. Walking back through dp gives an order to add people in;
 * every point where the running total is zero ends a group.
 */
function zeroSumGroups(people) {
  const n = people.length;
  if (n === 0) return [];
  const full = (1 << n) - 1;

  const sum = new Float64Array(1 << n);
  const dp = new Int8Array(1 << n);
  for (let mask = 1; mask <= full; mask++) {
    const low = 31 - Math.clz32(mask & -mask);
    sum[mask] = sum[mask & (mask - 1)] + people[low][1];
    let best = 0;
    for (let i = 0; i < n; i++) {
      if (mask & (1 << i) && dp[mask ^ (1 << i)] > best) best = dp[mask ^ (1 << i)];
    }
    dp[mask] = best + (sum[mask] === 0 ? 1 : 0);
  }

  // Recover the order people were added in (back to front).
  const order = [];
  for (let mask = full; mask; ) {
    const gain = sum[mask] === 0 ? 1 : 0;
    for (let i = 0; i < n; i++) {
      if (mask & (1 << i) && dp[mask ^ (1 << i)] + gain === dp[mask]) {
        order.push(i);
        mask ^= 1 << i;
        break;
      }
    }
  }
  order.reverse();

  // Keep people in first-seen order inside each group so output is predictable.
  const groups = [];
  let current = [];
  let running = 0;
  for (const i of order) {
    current.push(i);
    running += people[i][1];
    if (running === 0) {
      groups.push(current.sort((a, b) => a - b).map((j) => people[j]));
      current = [];
    }
  }
  return groups.sort((a, b) => people.indexOf(a[0]) - people.indexOf(b[0]));
}

/**
 * Settle one zero-sum group: repeatedly have the person who owes the most pay
 * the person owed the most. Each payment clears at least one person and the
 * last clears two, so a group of k people needs at most k - 1 payments.
 */
function settleGroup(group) {
  const owes = group.filter(([, b]) => b < 0).map(([name, b]) => ({ name, left: -b }));
  const owed = group.filter(([, b]) => b > 0).map(([name, b]) => ({ name, left: b }));
  const biggest = (list) =>
    list.reduce((best, p) => (p.left > best.left ? p : best), { left: 0 });

  const payments = [];
  for (;;) {
    const from = biggest(owes);
    const to = biggest(owed);
    if (!from.left || !to.left) break;
    const paise = Math.min(from.left, to.left);
    payments.push({ from: from.name, to: to.name, amount: paise / 100 });
    from.left -= paise;
    to.left -= paise;
  }
  return payments;
}

module.exports = { settleUp };

Common mistakes (real)

Mistake What you see Why Fix
Trying one easy case by hand sum: 99.99 The hard case was never tried Tests for tricky inputs
Trusting tests the AI didn't run 1 failed, 15 passed "I haven't run the tests" Run them yourself, always
Exact equality on floats Expected: 28333.999999999996 / assert 2399.3999999999996 == 2399.4 Decimals aren't stored exactly Whole paise, or toBeCloseTo / pytest.approx
"Make the tests pass" (correct code gets changed) The test was wrong Ask: code or test? Check by hand
Letting the AI edit your test (the test gets weaker) Easiest way to go green "Don't edit "
Green = done Ravi pays Ravi ₹300 Edge case never tested Your own edge-case tests

Mini project

Add tests to one of your own projects:

  1. Install a test runner: npm install --save-dev jest and "test": "jest" in package.json, or pip install pytest.
  2. Ask the AI for tests of one function. Run them yourself. If any fail, decide: code or test?
  3. Write three edge-case tests of your own (zero, a messy string, an awkward decimal). Make at least one fail first, then fix the code.

Practice questions

  1. What is the difference between toBe and toEqual in Jest?
Answer

toBe checks exact identity with Object.is (fine for numbers and strings); toEqual compares the contents of objects and arrays. expect([1,2]).toBe([1,2]) fails, toEqual passes.

  1. Write a test that splitBill(1, 3) adds up to exactly 100 paise.
Answer
test('1 rupee among 3 adds up', () => {
  const paise = splitBill(1, 3).reduce((s, x) => s + Math.round(x * 100), 0);
  expect(paise).toBe(100);
});
  1. A test fails. List three things to check before asking the AI to fix the code.
Answer

The right answer worked out by hand; whether the test itself is correct (e.g. float comparisons, wrong expected value); and that you're running the latest code (saved files, right folder).

  1. Why does 0.1 + 0.2 === 0.3 print false in JavaScript?
Answer

0.1 and 0.2 can't be stored exactly in binary floating point; their sum is 0.30000000000000004.

  1. Name four edge cases for a function that splits a bill.
Answer

0 people (should throw), a total of 0, a total that doesn't divide evenly (100 among 3), more people than paise (0.02 among 3), a negative total, a total with 3 decimals, names with spaces.

Quiz

A test fails: Expected 28333.999999999996, Received 28334. What first? A) Tell the AI "make the tests pass" · B) Delete the failing test · C) Check the right answer by hand: code or test? · D) Run it again until it's green

Answer

C. Work out the right answer yourself. Here the code was right and the test compared floats exactly; "fixing" the code would have broken it.

Interview questions

  1. What makes a good unit test? Fast, independent, tests one behaviour, has a clear name, and a known expected value.
  2. How do you test code that handles money? Use integers in the smallest unit (paise/cents) or a decimal type; never compare floats exactly.
  3. What is TDD? Write a failing test for the behaviour you want, write the minimum code to pass, then refactor.
  4. Can 100% passing tests guarantee no bugs? No: tests only check the cases someone wrote. Edge cases, integration and UI need their own checks.
  5. How do you review AI-written tests? Run them; check they assert real expected values (not just "doesn't crash"); check edge cases; make sure a deliberately broken implementation makes them fail.

Glossary

Term Meaning (with an example from this episode)
Unit One small part of a program, usually one function (splitBill).
Unit test Code that runs one unit with a known right answer and reports pass/fail.
Assertion A statement that must be true in a test: expect(x).toEqual(y), assert a == b.
Test runner A tool that finds and runs tests and reports results (Jest, pytest).
Test suite All your tests together (Jest: each test file is a suite).
Jest A popular JavaScript test runner; npm test runs it here.
pytest A popular Python test runner; runs test_*.py files.
describe / test Jest functions that group tests and define one test.
Matcher The check in a Jest assertion: toBe, toEqual, toThrow, toBeCloseTo.
toBe Exact equality using Object.is.
toEqual Compares the contents of arrays/objects.
toThrow Passes if the code throws an error.
npm test Runs the test script from package.json.
Green / red All tests pass / at least one fails.
Failing test A test whose assertion was false; read name, expected, received, line.
Floating point How computers store decimals in binary; most decimals are approximate (0.1 + 0.2 = 0.30000000000000004).
Paise 1/100 of a rupee; storing money in whole paise avoids float errors.
toFixed(n) Rounds a number to n decimals and returns text.
toBeCloseTo / pytest.approx Compare decimals allowing a tiny difference.
Edge case An unusual input at the limits: 0, empty, huge, messy text.
Test-driven development (TDD) Write the failing test first, then the code.
@pytest.mark.parametrize Runs one pytest function for many inputs.
Manual test checklist Things you check by hand that unit tests can't see (looks, phones, messages).
Brute force Trying every possibility; the AI's tests used it to check the minimum payments.

Summary

  • Trying it once by hand is not testing; a unit test is code + a known right answer, run every time.
  • Jest and pytest find and run all tests in a second. Let the AI write tests, you run them.
  • A real AI mistake: its own test compared floats exactly and failed while the code was right. Check by hand: code or test?
  • Green tests miss what nobody tested: write your own edge cases, ideally first (TDD), and tell the AI not to edit them.
  • Money in whole paise. Keep a manual checklist for what tests can't see.

Next episode: Security mistakes AI makes: leaked keys, SQL injection, XSS, missing auth checks, open database rules, risky packages and a launch checklist.