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

JavaScript - unable to view updated information without refreshing page

I am currently developing a Single Page Application (SPA) using Rails for the backend and JavaScript for the frontend. When I submit the initial form to create a Resource, it shows up on the page immediately upon pressing the submit button. However, when I ...

Exploring bugs in Angular 14 through unit testing

After generating a new Angular project using the CLI ng new ..., I encountered an error when running npm test. The error appeared in the browser: and in the console as well: I haven't made any additional changes to the project. I tested with Node ve ...

The Bootstrap carousel is experiencing compatibility issues with Angular 7 and is currently not functioning properly

I'm currently using the bootstrap multi carousel, and it works perfectly without a loop. However, when I try to implement it dynamically using an ngFor loop, it doesn't function as expected. Instead of sliding with multiple images, it just displa ...

display a different selection option depending on the previously chosen item

I'm working on displaying additional options in a select box when the user makes a selection from the main select box. I've set display:none for the select boxes, which will only appear when the user chooses an option from the main select box. C ...

Setting the base URL in Next.js according to an environment variable: a step-by-step guide

I currently have a Strapi backend and Next.js frontend application deployed on DigitalOcean. Within DigitalOcean, I have configured an environment variable for the frontend: API_URL = ${APP_URL}/api To generate the base URL, I retrieve this variable using ...

"Enhancing User Interaction with AngularJS: Leveraging ng-click and ng

Currently, I have a map with markers that trigger an overlay-div to open when clicked. <div class="map" ng-init="loadall()"> <a ng-click="details.show=!details.show" href="#/dealer/{{marker.id}}" class="marker" style="left:{{marker ...

using Angular and RxJS to filter out an element from an array

One of the functions in my service is a delete function. This function calls an API that returns either true or false. If the response is true, I then proceed to find the index of the item in my array, splice it out, and return the updated array. Here&apos ...

Having difficulty encapsulating three.js rendered particles within a single div

I'm facing an issue where the particles generated by my three.js project are not contained within a specific div or html element as intended. Instead of staying within the designated boundaries, the particles are spreading across the entire DOM witho ...

Analyzing objects within an array for similarities

Suppose I have an array containing objects: var arr = [ { id: 1, pt: 0 }, { id: 2, pt: 12 }, { id: 3, pt: 7 }, { id: 4, pt: 45 }, { id: 5, pt: 123 }, ]; I am looking to loop through this array (possibly using array.forEach or array.map) ...

Is your AngularJS code throwing an error?

$scope.logout = function () { //var auth_token = $cookieStore.get('auth_token'); Auth.delete({ 'auth_token': $cookieStore.get('auth_token') }, function(data){ $scope.isLoggedIn = false; $cookieSto ...

What is the variance in performance between the sx prop and the makeStyles function in Material UI?

I recently started delving into Material UI and learned that it employs a CSS in JS approach to style its components. I came across 2 methods in the documentation for creating styles: First, using the sx prop: <Box sx={{ backgroundColor: 'green& ...

Tips for binding to a single input box within an ngFor loop

Can anyone lend a hand with some code? I'm working on a straightforward table using ngFor, but I'm facing an issue with input binding. The problem is that all the input fields generated by ngFor display the same value when typing. How can I preve ...

Having trouble loading popper.js using Laravel mix and webpack

I have been working on my project with Bootstrap 4 beta and Laravel 5.4, using npm and Laravel mix to load my JavaScript dependencies. Everything was going smoothly until I encountered an error while trying to use Bootstrap JavaScript methods. The error me ...

Obtaining the mouse position in JavaScript in relation to the website, preferably without relying on jQuery

I came across this code snippet on Ajaxian, but I am having trouble using cursor.y (or cursor.x) as a variable. When I call the function with it that way, it doesn't seem to work. Could there be a syntax issue or something else causing the problem? f ...

Distinguishing between the practical aspects of directly subscribing to an Observable versus employing the subscribe() method with a parameter

I have a function that provides data in an Observable: getData (): Observable<Data[]> {...} To utilize this data in my template and ensure the template remains "live" based on the Observable, I have come across two methods. I created a Subject ins ...

What steps can be taken to eliminate a npm install error?

I have been attempting to execute the following project: https://github.com/kentcdodds/react-in-angular This repository serves as an illustration of incorporating React into AngularJS. It consists of three tags that demonstrate the process of transitio ...

Looping in REACT with state updates can cause the values to be overwritten

I'm encountering a problem with my function in React that updates the state. It fetches data from a URL in an array and creates a new item, but when trying to update another state array with this new object, it keeps overriding the first item each tim ...

Issue with generating PDF in AngularJS: pdfMakeTypeError occurs due to inability to read 'ownerDocument' property within html2canvas

Whenever I try to export by clicking the export button, this code is triggered: $scope.export = function() { html2canvas(document.getElementById('balanceSheet')).then(function(canvas) { document.body.appendChild(canvas); ...

Guide to creating a Discord bot that replies privately to users without other channel members being able to see the messages

As a newcomer to Discord, I am attempting to create a bot that will respond to user commands by sending a reply that only the user who issued the command can see. However, I am struggling to figure out how to implement this feature. Below is the source c ...

Is there a way to display "not found" if the code's output is blank?

Incorporating an "ajax select" and "while scrolling load data" script has been successful for me. However, I'm struggling with displaying a "not found data" message in div.status when the output variable on animals.php is empty. index.html <!DOCT ...