Performance: Why DI makes testing easier
Dependency Injection (DI) affects how easily components can be isolated and tested without loading unnecessary dependencies, improving test execution speed and reliability.
class UserComponent { constructor(userService) { this.userService = userService; } getUser() { return this.userService.fetchUser(); } } // In tests, inject a mock userService instead of real one
class UserComponent { constructor() { this.userService = new UserService(); } getUser() { return this.userService.fetchUser(); } }
| Pattern | Dependency Loading | Test Setup Time | Test Execution Speed | Verdict |
|---|---|---|---|---|
| Direct instantiation inside component | Loads all real dependencies | High | Slow | [X] Bad |
| Dependency Injection with mocks | Loads only mocks | Low | Fast | [OK] Good |
component.getData() if mockService.getData() returns 'test data'?
const mockService = { getData: () => 'test data' };
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{ provide: RealService, useValue: mockService }]
});
component = TestBed.inject(MyComponent);
});
// In component:
getData() {
return this.realService.getData();
}beforeEach(() => {
TestBed.configureTestingModule({
providers: [RealService]
});
component = TestBed.inject(MyComponent);
component.realService = { getData: () => 'mocked' };
});Pass the test and this pattern moves unknown