StoicBuilder
Later missionMission 28: Tests that charge nobodyYou can practise it now. It counts once you reach mission 28, after “First day on the Harbor team”.Back to HQ
Exit lesson
Mocks, stubs and fakesProLesson 23 of 45, about 8 min
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
0 XP

The app: Bench, a test runner

Benchharbor / billingVitest
send-invoice.test.js

What the tests use

payments.chargeReal APICalls the payment provider in test mode, over the network.
email.sendRealSends a real email.

Not run yet.

  • a paid invoice gets a receipt

The code, the tests and what left the test

billing/send-invoice.js the code under testsendInvoice
1import { invoiceTotal } from "./invoice-total";2 3// The services come in as arguments, so a test can pass in doubles.4export async function sendInvoice(invoice, { payments, email }) {5 const total = invoiceTotal(invoice);6 const charge = await payments.charge({ amount: total, idempotencyKey: invoice.id });7 if (charge.status !== "succeeded") {8 return { id: invoice.id, status: "unpaid" };9 }10 await email.send({ to: invoice.email, invoiceId: invoice.id, amount: total });11 return { id: invoice.id, status: "paid", chargeId: charge.id };12}
billing/send-invoice.test.js the tests1 test
1import { expect, test, vi } from "vitest";2import { sendInvoice } from "./send-invoice";3import { payments } from "./payments"; // the real API, test mode4import { email } from "./email"; // sends for real5 6const invoice = { id: "inv_2041", email: "dana@okafor-design.example", seats: 4 };7 8test("a paid invoice gets a receipt", async () => {9 const result = await sendInvoice(invoice, { payments, email });10 expect(result.status).toBe("paid");11});
Terminal npx vitest run billingnot run

Nothing has run yet. Press Run tests.

Network requests that left the testnone yet

Requests show here when the tests run.

The MagisterBench again, on sendInvoice: it charges a card through the payment API, then emails a receipt. Its one test passes. Press Run tests and read the Network section: a charge in the provider’s test mode, and a real email to a customer whose address was copied into the test data. Tap the email.

Step 1 of 7Run the test as it is
  • Run the tests
  • Tap the email request

You’re not signed in, so this lesson won’t be saved to your path. Sign in free to keep your XP.