Sikau

NestJS · Day 12 · about 35 min

Testing with mocks

Test a service in isolation by faking its dependencies.

DI pays off

Because services receive their dependencies, a test can hand them a mock — a fake payments client, a fake repository — and check the logic without touching real money or a real database. Nest's Test.createTestingModule builds just the pieces you need.

createTestingModule + overrideProvider

import { test } from "node:test";
import assert from "node:assert/strict";
import { Test } from "@nestjs/testing";
import { CheckoutService, PaymentsService } from "./checkout";

test("charges the order total", async () => {
  const charges: number[] = [];
  const moduleRef = await Test.createTestingModule({ providers: [CheckoutService, PaymentsService] })
    .overrideProvider(PaymentsService)
    .useValue({ charge: async (amount: number) => { charges.push(amount); return "ok"; } })
    .compile();

  const checkout = moduleRef.get(CheckoutService);
  await checkout.pay([{ price: 180, qty: 2 }]);
  assert.deepEqual(charges, [360]);
});

The rest of this lesson

  • Arrange, act, assertexplain
  • Unit tests and end-to-end testsexplain
  • Why mock payments?predict
  • Order the testorder
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of NestJS