0
0
Angularframework~8 mins

Mocking services in tests in Angular - Performance & Optimization

Choose your learning style9 modes available
Performance: Mocking services in tests
LOW IMPACT
Mocking services in tests affects test execution speed and resource usage during development, not the actual page load or runtime performance.
Testing a component that depends on a service
Angular
import { of } from 'rxjs';

class MockService {
  getData() { return of(['mock', 'data']); }
}

beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [{ provide: RealService, useClass: MockService }]
  });
});

it('should test with mock service', () => {
  const service = TestBed.inject(RealService);
  // fast, no real HTTP calls
});
Mocks avoid real logic and network calls, making tests faster and lighter.
📈 Performance Gaintests run faster, lower CPU and memory usage
Testing a component that depends on a service
Angular
beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [RealService]
  });
});

it('should test with real service', () => {
  const service = TestBed.inject(RealService);
  // real HTTP calls or heavy logic executed
});
Using the real service runs actual logic or HTTP calls, slowing tests and increasing resource use.
📉 Performance Costtests block longer, higher CPU and memory during test runs
Performance Comparison
PatternTest Execution TimeResource UsageNetwork CallsVerdict
Real service in testsLonger due to real logicHigher CPU and memoryPossible real HTTP calls[X] Bad
Mocked service in testsShort and fastLow CPU and memoryNo network calls[OK] Good
Rendering Pipeline
Mocking services in tests does not affect the browser rendering pipeline since it runs only during test execution, not in the browser runtime.
⚠️ Bottlenecknone
Optimization Tips
1Always replace real services with lightweight mocks in tests to speed up execution.
2Avoid real HTTP calls or heavy logic during tests to reduce CPU and memory usage.
3Mock only what is necessary to keep tests fast and maintainable.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of mocking services in Angular tests?
ATests run faster by avoiding real service logic and network calls
BImproves page load speed in production
CReduces CSS paint times
DDecreases JavaScript bundle size
DevTools: Performance
How to check: Run tests with Angular CLI and open browser DevTools Performance panel to record test execution if running in browser; alternatively, use Node.js profiling tools for CLI tests.
What to look for: Look for long CPU tasks or network activity during tests indicating real service calls instead of mocks.