How do you write a unit test for a component or a service in Angular?

Angular testing, tooling and architecture · Freshers

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