How do you test a Kancil Courier booking without sending a real SMS to a customer? As long as createBooking fetches its own SMS sender, you can't.
Dependency Injection (DI) means a function or object receives its dependencies from outside, instead of creating or fetching them itself. A dependency is another object it needs to do its job: a store, a message sender, a tracking number counter. Picture a cook in a restaurant kitchen. The ingredients are prepared and brought to the station; the cook doesn't run to the market in the middle of cooking. When a new cook is tested, practice ingredients are brought instead, and the recipe stays exactly the same. A cook who goes shopping for every order can't be tested without a market.
The problem: a createBooking that fetches for itself
The old version of Kancil Courier's booking core fetched everything it needs itself, including TrackingCounter from the Singleton lesson:
function createBooking() {
return {
book({ recipient, phone, service, kg }) {
if (!Object.hasOwn(RATES, service)) throw new Error("Unknown service: " + service)
const trackingNo = TrackingCounter.getInstance().next() // singleton
const shipment = { trackingNo, recipient, phone, service, kg, cost: kg * RATES[service], status: "picked_up" }
shipmentDb.set(trackingNo, shipment) // a global Map
smsAdapter.notify(phone, trackingNo + " picked up, shipping $" + shipment.cost) // the production adapter
return shipment
},
}
}
The test tries to hand it an in-memory store and a fake notifier, createBooking({ store: createInMemoryStore(), notifier: fake }), but JavaScript quietly ignores arguments nobody asked for. Two tests, each booking one parcel and expecting KCL-0001:
SMS gateway → 07700900123: KCL-0001 picked up, shipping $36
fail: express 2 kg: KCL-0001 $36, messages recorded 0
SMS gateway → 07700900456: KCL-0002 picked up, shipping $30
fail: regular 3 kg: KCL-0001 $30, got KCL-0002 $30
Two real SMS left the app from a test, the fake recorded 0 messages, and the second test got KCL-0002 because the singleton carried the count over from the first test. From its line alone, createBooking() doesn't say it needs a counter, a database and an SMS vendor.
DI: the dependencies are passed in from outside
You already wrote DI in the Ports & Adapters lesson, you just didn't name it:
function createBooking({ store, notifier }) {
return {
book({ recipient, phone, service, kg }) {
if (!Object.hasOwn(RATES, service)) throw new Error("Unknown service: " + service)
const trackingNo = store.nextTrackingNo()
const shipment = { trackingNo, recipient, phone, service, kg, cost: kg * RATES[service], status: "picked_up" }
store.save(shipment)
notifier.notify(phone, trackingNo + " picked up, shipping $" + shipment.cost)
return shipment
},
}
}
// main.js: the only place that assembles
const booking = createBooking({ store: createApiStore(api), notifier: smsAdapter })
// booking.test.js: the test assembles its own version
function setup() {
const sent = []
const booking = createBooking({
store: createInMemoryStore(), // a fresh tracking counter for every test
notifier: { notify: (phone, message) => sent.push(message) }, // fake: only records
})
return { booking, sent }
}
// pass: express 2 kg: KCL-0001 $36
// pass: regular 3 kg: KCL-0001 $30
createBooking({ store, notifier })writes its needs in its parameters. Anyone reading that line knows what to prepare.main.jsis the composition root: the one place that picks the production dependencies and assembles them.- The test assembles its own version with an in-memory store and a fake: 2 of 2 pass, 0 real SMS.
- The singleton from the Singleton lesson, rethought. The app can still have exactly one store:
main.jsmakes it once and passes it to everything that needs it. The difference is that "only one" is now decided inmain.js, not locked inside the class withgetInstance(), so every test is free to make a new store that starts atKCL-0001.
The name Dependency Injection comes from Martin Fowler's 2004 article "Inversion of Control Containers and the Dependency Injection pattern". Inversion of Control means control is turned around: it's not createBooking that looks for its dependencies, it's the caller that provides them.
Three ways to pass them in
class BookingService {
constructor(store, notifier) { // 1. constructor injection: required, passed in at creation
this.store = store
this.notifier = notifier
}
setLogger(logger) { // 2. setter injection: optional, plugged in afterwards
this.logger = logger
}
printLabel(shipment, printer) { // 3. method injection: changes with every call
printer.print(shipment.trackingNo + " " + shipment.recipient)
}
}
- Constructor injection for required dependencies: the object never exists half-built.
createBooking({ store, notifier })is the function version, the exercise'sUserServiceis the class version. (Field injection in frameworks like Spring fills properties without going through the constructor, so the needs don't show; for required dependencies still pick the constructor.) - Setter injection for optional dependencies, a logger for example. Between
newandsetLogger, the object isn't complete. - Method injection for a dependency that changes with every call, a printer that differs per warehouse for example.
Container: automatic assembly, still in main.js
When there are dozens of dependencies that depend on each other, assembling by hand in main.js gets long. A DI container keeps a recipe for making each dependency, then assembles them on request:
function createContainer() {
const factories = new Map()
const instances = new Map()
return {
register(name, factory) { factories.set(name, factory) },
resolve(name) {
if (!instances.has(name)) instances.set(name, factories.get(name)(this))
return instances.get(name)
},
}
}
// main.js
const container = createContainer()
container.register("store", () => createApiStore(api))
container.register("notifier", () => smsAdapter)
container.register("booking", (c) => createBooking({ store: c.resolve("store"), notifier: c.resolve("notifier") }))
const booking = container.resolve("booking")
registerstores a recipe.resolveruns the recipe once and keeps the result ininstances, sostoreis made once per container: a singleton managed by the container, not by its own class.createBookingdoesn't change by a single line, and its tests still assemble directly, without a container. For two dependencies this container is longer than one line of hand assembly: start with plain arguments, reach for a container when the assembly grows.
Service locator: a hidden dependency
A service locator also has register and get, but it is called from inside the core:
const locator = {
services: new Map(),
register(name, service) {
this.services.set(name, service)
},
get(name) {
if (!this.services.has(name)) throw new Error("Service not registered: " + name)
return this.services.get(name)
},
}
// bootstrap.js: runs when the app loads, and during tests too
locator.register("store", createApiStore(api))
locator.register("notifier", smsAdapter)
createBooking() goes back to having no parameters, and book fetches const store = locator.get("store") and const notifier = locator.get("notifier") itself; the rest is the same as the DI version. The test registers locator.register("store", createInMemoryStore()) but forgets the notifier, then books two parcels. Take a guess first: does the test pass or fail, and how many real SMS go out?
The result: pass twice, 2 of 2, and 2 real SMS sent (SMS gateway → 07700900123: KCL-0001 picked up, shipping $36, then one more to 07700900456). The locator still holds smsAdapter from bootstrap, and nothing in createBooking() says it needs a notifier. In the DI version, a forgotten notifier can't slip through: the test stops with TypeError: Cannot read properties of undefined (reading 'notify') and 0 SMS are sent.
Fowler (2004) compares the two approaches; Mark Seemann (2010) calls the service locator an anti-pattern because its dependencies are hidden from the signature, so they're hard to see and hard to swap for fakes in tests. What tells them apart is who calls it: a container called only in main.js is DI, a container passed into createBooking and resolved there is a service locator again.
💡 In frameworks: Laravel and Angular
- Laravel reads the type hints in a constructor (
public function __construct(ShipmentStore $store)) and builds the object itself.$this->app->bind(ShipmentStore::class, ApiShipmentStore::class)picks the implementation,$this->app->singleton(...)builds it once, and in a test$this->app->instance(ShipmentStore::class, $fake)swaps it for a fake. - Angular has a built-in injector: a component asks for a dependency through its constructor parameters or
inject(ShipmentStore), and in testsTestBedcan supply a fake provider.
Exercise: UserService with constructor injection
The exercise uses the class version:
createFakeRepo(): an in-memory stand-in store. Return{ users, find, save }:usersis an array readable from outside,find(id)returns the user with thatidornull, andsave(user)gives it a sequentialidstarting at 1, stores{ id, name }and returns it.class UserService:constructor(userRepository)only keeps the repo passed in, inthis.userRepository.getUserName(id)returns thenamefromthis.userRepository.find(id), or"Unknown"when that isnull.register(name)returns the result ofthis.userRepository.save({ name }).
The starter registers Budi and Ani, so the console shows Budi, Ani, Unknown (for id 999), then 2 (the size of repo.users).
⚠️ Dependencies that get fetched from inside again
- A default that points at production.
function createBooking({ store, notifier = smsAdapter })looks handy, but a test that forgets the notifier quietly sends real SMS, exactly like a service locator. - A container passed inside.
createBooking(container)withcontainer.resolve("notifier")inside it is a service locator. Call the container only inmain.js. - A dependency list that keeps growing. A function that needs seven dependencies is usually doing too much. Split the function; don't hide its dependencies.
- In the exercise: building the repo inside the constructor.
this.userRepository = createFakeRepo()ignores the repo passed in, so the test'srepo.usersdoesn't grow and theSari|1|Unknowncheck becomesSari|0|Unknown. The ids must also start at 1, not 0.
TL;DR: Dependency Injection: a function or object receives its dependencies from outside (createBooking({ store, notifier }), new UserService(repo)) instead of creating or fetching them itself. Its needs show in its signature, main.js assembles the production version, and tests assemble their own with an in-memory store and a fake: 2 of 2 pass, 0 real SMS. Constructor injection for required dependencies, setter injection for optional ones, method injection for ones that change with every call. The TrackingCounter.getInstance() singleton is replaced by a store made once in main.js, so every test can start at KCL-0001. A container (Laravel, Angular, or a tiny createContainer) only automates the assembly and is still called in main.js. A service locator (locator.get("notifier") inside the core) hides dependencies: a test that forgets to register a fake still passes while sending 2 real SMS.
⚡ A core that fetches for itself
Guess first: createBooking() fetches TrackingCounter, a global database and smsAdapter by itself. A test hands it an in-memory store and a fake notifier. What happens?
The arguments are quietly ignored. Two real SMS leave the app from the test, the fake records 0 messages, and the second test gets KCL-0002 because the singleton carried the count over from the first.
Meaning: From its line alone, createBooking() doesn't say it needs a counter, a database and an SMS vendor.
⚡ Dependencies passed in from outside
Write:
function createBooking({ store, notifier }) {
return {
book({ recipient, phone, service, kg }) {
if (!Object.hasOwn(RATES, service)) throw new Error("Unknown service: " + service)
const trackingNo = store.nextTrackingNo()
const shipment = { trackingNo, recipient, phone, service, kg, cost: kg * RATES[service], status: "picked_up" }
store.save(shipment)
notifier.notify(phone, trackingNo + " picked up, shipping $" + shipment.cost)
return shipment
},
}
}
Meaning: Dependency Injection: an object receives its dependencies from outside, it doesn't create them itself inside. main.js assembles the production version, tests assemble their own with an in-memory store and a fake: 2 of 2 pass, 0 real SMS.
⚡ A service locator hides dependencies
Meaning: A container called only in main.js is still DI. When locator.get("notifier") is called from inside the core, the dependencies are hidden from the signature, and a test that forgets to register a fake still passes while sending real SMS.