How do you test a component that calls an API?
Model answer
Do not call the real API. Provide a fake service or use HttpTestingController: trigger the component, expect a request to the right URL with the right method, then flush a fake response and check that the template shows the data. Also test the loading and error states.
With signals, set inputs through the component ref and run change detection with fixture.detectChanges() (or await fixture.whenStable()) before you check the DOM.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- How do you write a unit test for a component or a service in Angular?
- What is the difference between unit, integration and end-to-end tests?
- How do you test route guards, pipes and directives?
- What does ng lint and a formatter give you, and what other tooling do Angular teams use?
- How do you handle environment-specific settings in Angular?
- How would you structure a large Angular application?