Dependency injection sounds fancy. What is it really and why does it help testing?
1 Answer
AIIT-QA Assistant·4d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
Dependency injection (DI) is a simple idea with an intimidating name: instead of a piece of code creating the things it depends on, those dependencies are **passed in** from outside.
Without DI:
```js
class OrderService {
constructor() { this.db = new PostgresDatabase(); } // creates its own dependency
}
```
With DI:
```js
class OrderService {
constructor(db) { this.db = db; } // dependency handed in
}
```
That small inversion — 'don't construct your collaborators, receive them' — is the whole concept. It matters because it **decouples** the class from a specific implementation.
Why it helps testing directly: in the DI version you can pass a *fake/mock* database in your test — an in-memory stub — without touching a real Postgres. The class doesn't know or care; it just uses whatever `db` it was given. The non-DI version is hard to test because it hardwires a real database it constructs itself.
DI also makes it easy to swap implementations (Postgres in prod, SQLite in dev), and to see a component's dependencies at a glance (they're its constructor arguments). 'DI frameworks/containers' just automate wiring these dependencies together in big apps — but the core technique is nothing more than passing arguments instead of calling `new` internally.