Testing actual HTTP requests in unit and integration tests with AngularJS

Attempting a request that was not mocked using $httpBackend.when in an Angular 1.x unit/integration test will lead to an error:

Error: Unexpected request: GET /real-request

Is there a way to perform actual HTTP requests with ngMock and the Karma+Jasmine testing setup? What is the recommended approach for achieving this?

Answer №1

The AngularJS framework has a strong stance on HTTP requests in unit testing - all requests should be mocked.

Performing real HTTP requests in unit tests is discouraged for two main reasons. Unit tests should be fast and isolated, and making a real request can slow down the test significantly by introducing asynchrony. Additionally, using real requests breaks the isolation as the test outcome relies on both the unit being tested and the backend service.

To address this issue, AngularJS introduced the ngMock module, automatically loaded in unit tests via angular-mocks.js. This module eliminates the need for developers to perform asynchronous Jasmine unit tests with Angular.

On the other hand, integration tests differ from unit tests as they may involve testing multiple units, potentially including a backend server through real HTTP requests. In such cases, Karma and Jasmine are still used, but the tests may run slower and require asynchrony.

In E2E tests, the ngMockE2E module comes into play. While included in angular-mocks.js alongside ngMock, it's not loaded by default. This module provides mocks suitable for end-to-end testing, with features like the e2e $httpBackend mock.

ngMockE2E offers an alternate implementation of $httpBackend for this purpose, with variations in its API usage. It's recommended not to use methods like flush and extend, and instead utilize $rootScope.$digest() for executing promises.

However, integrating ngMockE2E may face challenges due to adjustments made to Angular services by ngMock. To resolve this, a helper module for integration tests such as 'ngMockI9n' can be utilized.

For smoother testing practices, a recipe for whitelisting real HTTP requests can make the process easier, though explicit enumeration of real and mocked requests is considered best practice.

In summary, when conducting integration tests that involve real requests, it's advisable to leverage $httpBackend from ngMockE2E, albeit requiring additional steps to ensure compatibility with ngMock. Avoid real requests in unit tests to maintain the speed and quality of the tests.

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

How can I utilize a filter or pipe to populate product categories onto screens within Ionic 2?

I am considering creating an Ionic 2 app with 6 pages, but I'm unsure whether to utilize a Pipe or a Filter for the individual category pages and how to implement the necessary code. Each category page should be able to display products from the "app ...

capturing the HTML title and storing it in a JavaScript variable

Is there a way to retrieve the title "Some Name" in the JS file and have it be populated by the hyperlink's title attribute, which is set to "sometitle" in the HTML code? JS var randomtext={ titleText:"Some Name",} HTML <a class="css" title="so ...

We apologize, but Google Pay encountered an unexpected developer error that caused the request to fail. Please try again later

When attempting to make a payment using Google Pay on a real device in the TEST environment, I am encountering the error mentioned in the title. I have followed the guidance provided in the Google docs and tried converting 'gateway' to a string, ...

Refine the JSON data to only include the values you need

I've been spending a considerable amount of time on this challenge, but I'm facing difficulty in solving it. The issue at hand is that I have a JSON file that I am fetching from a URL, and my objective is to create a filter that displays only nam ...

Express.js app issue: post id assigns category name instead

Currently, I am in the process of developing a blogging application using Express, EJS, and MongoDB. To view the GitHub repository for this project, please click on this link. The posts within my application are organized into different categories, each r ...

Is it possible to modify the sizes parameter of the GPUComputationRenderer?

Currently, I am utilizing gpuCompute = new GPUComputationRenderer( sizeX, sizeY, renderer ); for texture purposes. I am looking to update the values of sizeX and sizeY within this code snippet. However, after searching through the library, I have not been ...

Data manipulation with Next.js

_APP.JS function MyApp({ Component, pageProps }) { let primary = 'darkMode_Primary'; let secondary = 'darkMode_Secondary' return ( <Layout primary_super={primary} secondary_super={secondary}> <Component {...page ...

An easy guide to animating multiple sections of progress bars individually in Bootstrap

My Bootstrap code successfully animates a section of progress bars when the user views it. However, it currently animates all progress bars on the page rather than just those in the viewed section. This means that when the user moves to another section, th ...

Utilizing Vue to Embed Multiple Hubspot Forms on one Page

While working on a Vue page, I encountered an issue with loading multiple Hubspot forms simultaneously. Only one form would load at a time. Here is the code snippet I used to append a single Hubspot form: mounted() { const script = document.createElem ...

Using pre-built modules in an environment that does not support Node.js

Despite the limitations on node API usage (such as fs, http, net...), vanilla JS can still be used on any engine. While simple functionalities can be easily extracted from packaged modules if licensing terms are met, things get complicated when dealing wit ...

What is the process for eliminating the invocation of a function in Jquery?

I am currently facing an issue with my application. When I launch the Ficha() function, it initiates an ajax call and works perfectly fine. However, another ajax call is made later to load HTML tags that also need to invoke the Ficha() function. The prob ...

What is the best way to create a unique custom control in Javascript, potentially utilizing jQuery?

My goal is to develop a custom control using JavaScript that includes methods, properties, and events, and can be rendered within a div element. For example, one such control could be a calendar. It would display in a div, with customizable properties for ...

Tips on managing the onKeyUp event in a ReactJS form

Here is a simple JavaScript function called numericOdds implemented in home.js file: function numericOdds(e) { var valid = /^[1-9]{1}[0-9]{0,1}$/ var number = /^[1-9]{1}$ | ^[1-9]{1}[0-9]{1}$/ var lastValid = ''; var n; console.log(&apo ...

Using AJAX and PHP to dynamically fill HTML drop-down menus

In order to populate the DropDown controls on my HTML Form dynamically, I have implemented a code that utilizes AJAX to make a call to a .php file. This .php file is responsible for filling the DropDown control with values from a single column. Throughout ...

Issue with retrieving data from MySQL database using PHP in Chart.js

I am currently facing an issue while trying to populate a chart using the ChartJS plugin with data from my MySQL database. I keep encountering the error message: mysqli_fetch_assoc(): Couldn't fetch mysqli_result in ... Despite using json_encode, ...

Oh no, Angular is giving us trouble!

Having trouble pulling in the contents of nav.html and footer.html from the include folder. All necessary files are located there. If anyone can offer assistance, it would be greatly appreciated. Thank you! ...

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...

Issue with AngularJS Cross-Origin Resource Sharing (CORS) when making HTTP requests, whereas standard Ajax and jQuery are

I'm currently dealing with a straightforward cross-domain service that is set up to handle Simple CORS requests. When I try to access it using a plain xmlHTTP call or jQuery($.ajax), everything works smoothly. However, when attempting to make the call ...

React: Should we use useCallback when creating a custom Fetch Hook?

Currently delving into the world of React on my own, I've come across this code snippet for a custom hook that utilizes the fetch() method. import { useState, useEffect, useCallback } from "react"; import axios from "axios"; funct ...

Issue encountered when attempting to update a specific element within an array using Mongoose

Looking to update a specific object within an array. { "_id": "543e2f8e769ac100008777d0", "createdDate": "2014-10-15 01:25 am", "cancle": false, "eventDateAndTime": "2014-02-12 12:55 am", "eventstatus": true, "userPhone": "44444444 ...