Not quite sure if using mergeMap
is the best approach here. It would be wise to verify that.
Here is my method of testing a function from a service that executes an HTTP request and returns an observable.
1 - Create a Mock HTTP client
Below is an illustration of how I handle this in an Angular project, leveraging TestBed
for dependency injection.
let httpClient: HttpClient;
let service: YourService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
...
}).compileComponents();
httpClient = TestBed.get(HttpClient);
service = TestBed.get(YourService);
});
2 - Spy on the mock function
To ensure the expected result from the get request, it's crucial to spy on it and provide a simulated outcome.
describe("WHEN: getAllChassis", () => {
beforeEach(() => {
const RESPONSE_MOCK = of(
new HttpResponse({
body: {
/* sample data your service provides */
},
})
);
spyOn(httpClient, "get").and.returnValue(RESPONSE_MOCK);
});
// Your test goes here
});
3 - Validate your function output
When testing your feature, ensure that it produces the expected result (considering the anticipated response from http.get).
Note the use of done
due to the async nature of the function. The test will only conclude when done is called (or upon timeout).
it("THEN: should return data", (done) => {
getAllChassis()
.pipe(take(1))
.subscribe((data) => {
expect(data).toEqual({
/* expected outcome */
});
done();
});
});