-
Notifications
You must be signed in to change notification settings - Fork 94
-
Hello, is there a way to mock backend responses?
In case of TestBed, when I have a component with service that calls backend, I use HttpTestingController to respond to a request. How do I go about it with testing library?
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 3 comments 1 reply
-
You can mock the service - see the examples https://github.com/testing-library/angular-testing-library/blob/main/apps/example-app/src/app/examples/12-service-component.spec.ts.
Another option is to use MSWjs - https://timdeschryver.dev/blog/using-msw-in-an-angular-project
Beta Was this translation helpful? Give feedback.
All reactions
-
https://github.com/testing-library/angular-testing-library/blob/main/apps/example-app/src/app/examples/12-service-component.spec.ts - mocks entire service, I would like to just mock backend.
Thank you.
Beta Was this translation helpful? Give feedback.
All reactions
-
You can mock HttpClient
using a spy object.
e.g. using Jasmine:
import { HttpClient } from '@angular/common/http'; const httpClient: jasmine.SpyObj<HttpClient> = jasmine.createSpyObj('HttpClient', ['post']); httpClient.post.and.returnValue('Mocked response'); // TODO: Provide httpClient on Angular Testing Library providers array. // { provide: HttpClient, useValue: httpClient }
Beta Was this translation helpful? Give feedback.
All reactions
-
You can use the injector
on the debugElement
of the object, the render
function returns.
const renderResult = await render(YourComponent, { providers: [provideHttpClient(), provideHttpClientTesting()], }) const http = renderResult.debugElement.injector.get(HttpTestingController);
Beta Was this translation helpful? Give feedback.