How do you write a unit test for a component or a service in Angular?
Model answer
Angular projects use a test runner such as Karma with Jasmine in older setups, or Jest or Vitest in newer ones. For a service with no dependencies you can create it with new or through TestBed and call its methods. For a component, TestBed.configureTestingModule configures imports and providers, createComponent builds it, and you check the rendered DOM and the component state.
Replace real dependencies such as HttpClient with fakes: provideHttpClientTesting with HttpTestingController lets you control responses.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- What is the difference between unit, integration and end-to-end tests?
- How do you test a component that calls an API?
- 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?