Tips for testing nested HTTP calls in unit tests

I am currently in the process of unit testing a function that looks like this:

async fetchGreatHouseByName(name: string) {
  const [house] = await this.httpGetHouseByName(name);
  const currentLord = house.currentLord ? house.currentLord : '957';
  const result: any = await this.httpGetLord(currentLord);
  const character = Characters.default.find(char => char.characterName === result.name);
  return {...house, character};
}

Within this function, there are several HTTP GET calls. While I have a grasp on how to test them individually, I am unsure how to handle nested HTTP Calls, each of which returns a Promise.

This is what I have tried so far:

it('should get house from http', done => {
  const httpMock: HttpTestingController = TestBed.inject(HttpTestingController);

  const mockResponse = {
    name: 'House One',
    currentLord: 'Some Lord'
  };

  service.fetchGreatHouseByName('House One').then((house: House) => {
    expect(house).toBeTruthy();
    console.log(house);
  });

  const mockRequest = httpMock.expectOne(
    'https://www.anapioficeandfire.com/api/houses?name=House%20Lannister%20of%20Casterly%20Rock'
  );

  mockRequest.flush(mockResponse);

});

So typically, httpGetHouseByName would return something similar to mockRequest. Whereas, httpGetLord returns an object containing name among other properties. Do I need another mock for this particular HTTP call and if so, how should I approach it?

Answer №1

When calling the function, it is recommended to queue up two HTTP calls. To ensure successful execution, try flushing both calls in a series and place your assertions within the .then block.

it('should retrieve house data from HTTP', done => {
  const httpMock: HttpTestingController = TestBed.inject(HttpTestingController);

  const mockResponse = {
    name: 'House One',
    currentLord: 'Some Lord'
  };

  service.fetchGreatHouseByName('House One').then((house: House) => {
    expect(house).toBeTruthy();
    console.log(house);
    // add other assertions here
  });

  const mockRequest = httpMock.expectOne(
    'https://www.anapioficeandfire.com/api/houses?name=House%20Lannister%20of%20Casterly%20Rock'
  );

  mockRequest.flush(mockResponse);

  const response = {
     // simulate response for httpGetLord
    };
  const request = httpMock.expectOne(/* URL of httpGetLord */);
  request.flush(response);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered while trying to exhibit jpg image content from server side on html

I am attempting to display an image from server-side data using an Ajax call. The data stored on the server looks something like this: "ÿØÿàJFIFÿÛC4­¶¸UOHlʵcBò)3¹_È'I4~&éüÿ§Ú<ã©ã4>'Øù¿ÇÄmËCÈgÚsZ¥ë" Upo ...

What is the best way to delay an observable from triggering the next event?

In my Angular project, I am implementing RxJs with two subjects. s1.next() s1.subscribe(() => { // perform some operation and then trigger the event for s2 s2.next() }); s2.subscribe(() => { // perform some operat ...

The FormGroup instance does not return any input method when using the get input function

I am facing an issue where a custom error message should only display if the input for foo is invalid. However, it seems like the line of code myForm.get('foo') is returning null. Below is the simplified version of component.html: <form [for ...

Always ensure that only one div is visible at a time

I am currently working on a project where I cannot use ng-cloak due to the way the css files are loaded. I have been exploring alternative solutions and have tried a few different approaches. My main goal is to ensure that two icons are never shown at the ...

Spread the picture on social media using Progressive Web App

I am currently working on a Nuxt PWA where I have implemented a function to convert HTML to Canvas using a specific package. The output generated is in base 64 format. My goal now is to find a way to easily share this image through various platforms such a ...

I have a JavaScript code that smoothly scrolls to different id's on a webpage, but I need assistance in adding an exception for a particular id

I'm looking to incorporate smooth scrolling for all hash links in my JavaScript. However, I need the id=nav and its resulting hash link, /#nav, to be exempt from this functionality as it interferes with the menu responsiveness. Can someone provide gui ...

What is the maximum file size that the data link is able to store?

For instance, a file like an image, video, or sound can be saved in the data link Take an image for example, it may be stored with the initial link: data:image/jpeg;base64,/..... followed by various characters. But, is there a specified size limit at whic ...

What is the best way to pass a div element and a variable from a Child component back to a Parent component in Next.js/React?

My goal is to create a webapp that, when an item in the list generated by the child component is clicked, displays the corresponding image in a div within the parent component. After some trial and error, I managed to generate the list in the child compone ...

Exploring the best practices for loading state from local storage in VueJS/NuxtJS by leveraging the "useLocalStorage" utility

When attempting to utilize useLocalStorage from pinia, I am encountering an issue where the data in the store's state is not fetched from local storage and instead defaults to the default value. Below is the code snippet from my store method: import ...

Ensuring React's setupProxy functions properly in conjunction with express.js

I've encountered an issue while trying to pass images from express to react. My express.static is correctly set up, so when I visit localhost:5000/public/images/me.jpeg, the image loads in my browser. However, when I attempt to use <img src="/publi ...

The pie chart fails to fully display

Check out the repro example I made here. The legend is displaying properly, but the graph is not showing up. What could be causing this unexpected issue? ...

The closest comparison to the For In method in JavaScript in the Apex programming

I am looking for a way in Apex to iterate through all the fields of a list of account objects without having to resort to using JavaScript. Currently, I can achieve this with the following code snippet in JavaScript, but I prefer to keep things within the ...

Angular - What causes variables to lose data after component changes?

Having an issue with two components - one creating and changing an array, and the other getting the array. The problem is that when retrieving the array in the second component, it only shows the default empty data. Code for array creation: export cla ...

Is it possible that I am making a mistake when using the multi-mixin helper, which is causing an unexpected compiler error that I cannot

As I work on creating a multi-mixin helper function that takes in a map of constructors and returns an extended map with new interfaces, I come across some challenges. Let's first look at the basic base classes: class Alpha { alpha: string = &ap ...

When working in React, I encountered a problem with the for of loop, as it returned an error stating "x is undefined." Although I could easily switch to using a simple for loop, I find the for of loop to

I'm encountering an issue when using a for of loop in React, as it gives me an error stating that "x is undefined". import { useEffect } from "react"; export default function HomeContent() { useEffect(() => { let content = document ...

Testing abstract class methods in Jest can ensure full coverage

In my project, I have an abstract generic service class. export default abstract class GenericService<Type> implements CrudService<Type> { private readonly modifiedUrl: URL; public constructor(url: string) { this.modifiedUrl = ...

The installed local Angular version is outdated compared to the current project version

I've been having trouble customizing my Angular CLI because a package I need only works with an older version of Angular. Currently, my global Angular version is 15.2.9. However, when I create a new Angular project using ng new, the package.json shows ...

Here's a way to resolve the issue: ReactDOM.render() - TS2345 error: Cannot assign type '() => Element' to type 'ReactElement' in the argument

After tackling React-Router with Typescript, I encountered a typing issue that has me perplexed. Prior to this, I was using an older version of React and React-Router. But now, after updating to the latest builds using yarn, I'm facing this hurdle. ...

Autocomplete is failing to provide any results

I am experiencing an issue with the autocomplete script as it is not displaying any names under the input field. Below is the code snippet from my index file: <head> <html lang="en"> <meta charset="utf-8"> <meta na ...

Tips for accessing the value stored within the parent element

As someone who is new to the world of javascript and typescript, I am currently working on an ionic application that involves fetching a list of values from a database. These values are then stored in an array, which is used to dynamically create ion-items ...