Mock HttpClient in a service component test in Angular?

Discussão em 'Angular' iniciado por Martin, Março 18, 2025.

  1. Martin

    Martin Guest

    Let's say I have a service that makes use of HttpClient,

    @Injectable()
    export class MyService {
    constructor(protected httpClient: HttpClient) { .. }
    }


    And then a component that makes use of this service.

    @Component({
    selector: 'my-component'
    })

    export class SendSmsComponent {
    constructor(private MyService) { .. }
    }


    How to test this component while mocking the HttpClient and not the whole service?

    TestBed.configureTestingModule({
    declarations: [MyComponent],
    providers: [
    { provide: MyService, useClass: MyService } // ?
    ]
    }).compileComponents();

    httpMock = TestBed.get(HttpTestingController); // ?

    Continue reading...

Compartilhe esta Página