Advertisement
Intermediate Angular, Services & Dependency Injection

How would you mock a service during testing to isolate a component from its real dependencies?

Short answer

You provide a fake, simplified version of the service in your test's configuration, replacing the real one, letting you control exactly what data or behavior the component receives during the test without depending on a real backend or complex real service logic.

Save Angular mock interview
Advertisement
AModel answer
You provide a fake, simplified version of the service in your test's configuration, replacing the real one, letting you control exactly what data or behavior the component receives during the test without depending on a real backend or complex real service logic.
TestBed.configureTestingModule({
  providers: [{ provide: UserService, useValue: { getUsers: () => of([{ name: 'Test User' }]) } }]
});
Real-world example
A component test replaces the real UserService, which normally makes a network request, with a simple mock object returning predictable fake data, letting the test run quickly and reliably without depending on any real backend.
Likely follow-ups
  • What is the difference between mocking a service with useValue versus using a spy object?
  • Why is isolating a component from its real dependencies considered good testing practice?
Related topics