Angular testing interview questions: TestBed, fixtures, HTTP mocks, and async tests

Reviewed by Mark Dickie · Last updated

5 questions on this page you can answer and see marked on the spot. Go to the first one

Angular testing is the practice of checking components, services, and routes with unit and integration tests before they ship. Interviewers mostly want to see that you can configure TestBed, drive a ComponentFixture through change detection, and replace real dependencies with spies or testing controllers. Expect to explain why a DOM assertion can fail until you call detectChanges(), and how fakeAsync makes timer-based code deterministic.

Which Angular testing APIs come up most in interviews?

API or setupWhat the interviewer wants you to explain
TestBed.configureTestingModuleWhich declarations, imports, and providers a component test needs, and how standalone components move them into imports.
ComponentFixture.detectChanges()Why the template stays stale until change detection runs, and what changes when autoDetect is on.
fakeAsync with tick() and flush()How to move past a setTimeout or debounce without real waiting, and why pending timers fail the test.
provideHttpClientTesting() with HttpTestingControllerHow expectOne() and verify() catch unexpected or unflushed requests.
jasmine.createSpyObjHow to stub a service dependency, then assert on calls and return values.
Stubbed ActivatedRouteHow to pass route params into a component under test without booting the router.

How would you practise these in a hands-on exercise?

  1. Test a service that calls HttpClient. Provide provideHttpClientTesting(), flush a fake payload with req.flush(), and assert on the mapped result.
  2. Test a component that emits an @Output. Trigger the button click, then check the emitted value with a Jasmine spy subscribed to the output.
  3. Test a debounced search box inside fakeAsync. Call tick(300) and assert that only one request reached the mock service.
  4. Run ng test --no-watch --code-coverage as you would in CI, and explain what a failing run looks like when a test leaves a timer pending.

Key facts

  • Tarmac has 11 Angular interview questions on this topic, 10 of them on this page, at difficulty 1–5 of 5.
  • Tarmac tracked 409 job postings asking for Angular in November 2026.
  • Roles asking for Angular advertise a median base salary of £67,500, across 62 job postings as of November 2026.
  • Tarmac last reviewed these Angular interview questions on 23 November 2026.

At a glance

Questions10 shown · 11 in the bank
Difficulty1–5 of 5
FormatsMultiple choice, Ordering, Multiple answer, Code output, True / false, Short answer, Fill in the blank, Flashcard, Coding exercise
Interactive1 run your code against tests, in the app

What you'll review

  1. spies mocking angular
  2. testbed

Practice questions

Try one before you open the answer. Pick an option and press Check; it's marked on the spot.

In an Angular unit test using Jasmine, which call creates a spy on the getUsers method of an existing userService object and makes it return a fixed value?#

Options

Show answer

In Jasmine, spyOn(userService, 'getUsers').and.returnValue(of([])) replaces getUsers with a spy that returns the given Observable whenever it's called. The spy also records each call, so the test can check it with expect(userService.getUsers).toHaveBeenCalled().

Why:

Jasmine's global spyOn(object, 'methodName') replaces the method with a spy, and chaining .and.returnValue(...) makes every call return the given value (here an Observable created with RxJS of). The other snippets aren't real APIs: methods don't have a .spy() method, TestBed has no spy function, and mock() isn't built into Jasmine or Angular.

Put these steps for a basic Angular component unit test with TestBed in the order they must run within a spec setup and test.#

Put these in order

Show answer

An Angular TestBed component test runs in this order: configure the testing module with TestBed.configureTestingModule, create the component with TestBed.createComponent, call fixture.detectChanges() to render bindings, then check the DOM. Configuration has to come first because TestBed locks it once a component exists, and the DOM only shows bound values after change detection has run.

Why:

The testing module must be configured first, because TestBed locks its configuration once a component is created. createComponent then instantiates the component and returns its fixture. The template isn't rendered with bindings until detectChanges() runs change detection. Only after that does the DOM hold the expected content you can assert on.

In a Jasmine-based Angular unit test, which matcher checks that a spy logSpy was called exactly twice?#

Options

Show answer

In Jasmine, expect(spy).toHaveBeenCalledTimes(2) checks that a spy was called exactly twice. toHaveBeenCalledWith checks the arguments, not the number of calls. spy.calls is a tracker object, so you read the count with spy.calls.count().

Why:

toHaveBeenCalledTimes(n) checks how many times the spy was invoked. toHaveBeenCalledWith(2) checks the arguments, so it would pass if the spy was called with the value 2, no matter how many times. logSpy.calls is a tracker object, not a number, so toBe(2) fails. toHaveBeenCalled() takes no count argument, and Jasmine throws an error if you pass one.

In an Angular unit test using Jasmine, you want to replace a real UserService dependency of a component with a test double. Which of the following approaches correctly do this? Select all that apply.#

Options

Pick every one that applies.

Show answer

You can mock an Angular service dependency in Jasmine tests in three ways. First, provide a jasmine.createSpyObj double with useValue. Second, call spyOn on the instance from TestBed.inject. Third, supply a fake class with useClass. Calling spyOn on the class itself (for example spyOn(UserService, 'getUser')) fails, because instance methods live on the prototype and not on the constructor.

Why:

A jasmine.createSpyObj object supplied via useValue replaces the dependency with a spy-only double. Calling spyOn on the instance returned by TestBed.inject stubs a method on the actual object the component receives. Supplying a fake implementation via useClass is also a standard DI-based substitution. Calling spyOn(UserService, 'getUser') on the class itself fails, because getUser is an instance method that lives on the prototype and not on the constructor. Jasmine throws an error saying the method does not exist. You would need spyOn(UserService.prototype, 'getUser') for this to work.

An Angular (v17, Zone.js-based) unit test uses TestBed with its default settings, so automatic change detection is NOT enabled. What does the test print to the console? Write each logged line on its own line.#

@Component({
  selector: 'app-title',
  standalone: true,
  template: `<h1>{{ title }}</h1>`
})
class TitleComponent implements OnInit {
  title = 'initial';
  ngOnInit() { this.title = 'loaded'; }
}

it('renders title', () => {
  TestBed.configureTestingModule({ imports: [TitleComponent] });
  const fixture = TestBed.createComponent(TitleComponent);
  const h1: HTMLElement = fixture.nativeElement.querySelector('h1');
  console.log(JSON.stringify(h1.textContent));
  fixture.detectChanges();
  console.log(h1.textContent);
});
Show answer
""
loaded
Why:

TestBed.createComponent creates the component and its DOM, but it does not run change detection. Bindings are not evaluated yet and ngOnInit has not run, so the <h1> is empty and JSON.stringify prints "". The first fixture.detectChanges() runs ngOnInit, which changes title to 'loaded', and then updates the binding. The same h1 element now has the text loaded. The text 'initial' never appears, because ngOnInit overwrites it before the first render.

In a Jasmine-based Angular unit test, calling spyOn(service, 'getUser') without chaining .and.callThrough() means the real getUser implementation is NOT executed when the method is called, and the spy returns undefined by default.#

Options

Show answer

Jasmine's spyOn(obj, 'method') replaces the method with a stub. By default the stub records calls and returns undefined, so the real implementation does not run. To execute the original code you chain .and.callThrough(). In Angular tests, spied service methods that should return Observables usually need .and.returnValue(of(value)).

Why:

Jasmine's spyOn swaps the original method for a stub. By default that stub records each call and returns undefined, and the real implementation never runs. To run the original code you chain .and.callThrough(), and to control the result you use .and.returnValue(...) or .and.callFake(...). A common mistake is a component test that expects an Observable from a spied service method but leaves out .and.returnValue(of(...)). The spy returns undefined, so subscribe throws a TypeError.

In an Angular unit test (Jasmine + TestBed), a component injects UserService in its constructor and calls this.userService.getUser(1).subscribe(...) inside ngOnInit. The test does:#

Show answer

The spy is installed too late. fixture.detectChanges() runs the first change detection, which triggers ngOnInit, so the real getUser already ran before spyOn replaced the method; the spy recorded no calls. Fix 1: get the service via TestBed.inject(UserService) and call spyOn(svc, 'getUser').and.returnValue(of(...)) BEFORE the first fixture.detectChanges() (the component and test share the same root/module-level singleton instance, so patching it works). Fix 2: don't provide the real service at all — create a mock with jasmine.createSpyObj('UserService', ['getUser']), set getUser.and.returnValue(of(...)), and register it with { provide: UserService, useValue: mockSvc }, then call detectChanges() and assert toHaveBeenCalledWith(1). This also avoids real HttpClient dependencies. (Note: if the service were provided in the component's own providers, you'd need fixture.debugElement.injector.get or TestBed.overrideComponent instead, since TestBed.inject would return a different instance.)

Why:

The first fixture.detectChanges() invokes lifecycle hooks including ngOnInit, so the method is called before spyOn patches it, and Jasmine spies only record calls made after installation. Installing the spy before the first change detection, or substituting a jasmine.createSpyObj mock via { provide, useValue }, makes the call go through the spy. A senior-level answer also notes that component-level providers create a separate instance that TestBed.inject doesn't return.

In Angular TestBed, ProfileComponent declares providers: [ProfileService] in its @Component metadata. ProfileService is also provided in root. To get the ProfileService instance that the component really uses, write fixture._____.injector.get(ProfileService), where fixture._____ is the DebugElement wrapper of the component's host element. Calling the current, non-deprecated TestBed method that resolves a service from the root test module injector, TestBed._____(ProfileService), returns the root-level instance, which is a different object. To replace the component-level provider with a stub, call TestBed._____(ProfileComponent, { set: { providers: [{ provide: ProfileService, useValue: stub }] } }). This call must come before the TestBed module is instantiated, which happens on the first TestBed._____(ProfileComponent) call, the one that creates the fixture.#

Show answer

In Angular TestBed, ProfileComponent declares providers: [ProfileService] in its @Component metadata. ProfileService is also provided in root. To get the ProfileService instance that the component really uses, write fixture.**debugElement**.injector.get(ProfileService), where fixture.**debugElement** is the DebugElement wrapper of the component's host element. Calling the current, non-deprecated TestBed method that resolves a service from the root test module injector, TestBed.**inject**(ProfileService), returns the root-level instance, which is a different object. To replace the component-level provider with a stub, call TestBed.**overrideComponent**(ProfileComponent, { set: { providers: [{ provide: ProfileService, useValue: stub }] } }). This call must come before the TestBed module is instantiated, which happens on the first TestBed.**createComponent**(ProfileComponent) call, the one that creates the fixture.

Why:

A provider listed in a component's providers array gets its own element injector, so each component instance receives its own service instance. That injector is reached through the DebugElement wrapper, fixture.debugElement.injector. The current TestBed.inject resolves from the root test module injector, so it returns a separate instance, and spying on it would not affect the component. Changing TestBed.configureTestingModule providers also does not replace component-level providers, so you need TestBed.overrideComponent with a set on providers. Overrides are only allowed before the TestBed module is instantiated, and TestBed.createComponent is the call that creates the fixture and instantiates the module; an override after that throws an error saying the module was already instantiated.

In an Angular TestBed test, you provide a spy for UserService with TestBed.configureTestingModule({ providers: [{ provide: UserService, useValue: spyObj }] }). However, UserProfileComponent lists UserService in its own @Component({ providers: [UserService] }). Why does the component still use the real service, and how do you make it use the spy?#

Show answer

Component-level providers create a new injector on the component's element. That element injector resolves UserService before the DI lookup ever reaches the TestBed module injector, so the component gets a real instance and the module-level spy is never used. To fix it, override the component's own providers: TestBed.overrideComponent(UserProfileComponent, { set: { providers: [{ provide: UserService, useValue: spyObj }] } }). You can also use TestBed.overrideProvider(UserService, { useValue: spyObj }), which applies to every level. Either call must happen before compileComponents() or createComponent(). To get the instance the component actually holds, use fixture.debugElement.injector.get(UserService), not TestBed.inject (which reads the root/module injector).

Why:

Angular's hierarchical DI looks in element injectors first and module or environment injectors second. A spy registered only in the testing module is therefore shadowed by the provider declared on the component, which is a subtle cause of mocks being silently ignored. Overriding the component's metadata, or calling overrideProvider, swaps the spy in at the injector level the component actually reads from.

Angular's TestBed follows strict lifecycle rules. Once the test module has been instantiated, which happens on the first TestBed.inject(...) or createComponent(...), any later call to configureTestingModule or overrideProvider throws, and only resetTestingModule makes the module configurable again. A provider set with overrideProvider also beats a provider registered with configureTestingModule for the same token, whichever call came first.#

Starter code

function simulateTestBed(ops) {
  const out = [];
  // TODO: track configured providers, overrides, and instantiation state
  return out;
}

Your solution must pass

  • override beats configure
  • override before configure still wins
  • failed inject still instantiates

This one is written and run, not read. Solve it in the app and your code is executed against these tests and the hidden ones.

Related interview questions

Job market

See angular salaries and hiring demand from live job postings.

The other 1 question

This page shows 10 and marks what you pick. That's as far as a page can go. A free account opens the other 1 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.

Start with this topic

Free · the whole bank · 100 answers per 30 days, each marked with written feedback

Interview booked? Practise the job ad instead

What moved, monthly

One email a month when the bulletin comes out: what moved in the markets we track, and the new question topics we published. Confirm your address to join. Unsubscribe any time.