Issue with Angular and Karma: HTTP GET request not running

Currently, I am working on an AngularJS project that utilizes Karma to execute some unit tests directly in the browser. To conduct these tests, I have opted for mocha as the test framework.

The challenge I am facing lies in running specification tests that require access to JSON files to verify if they conform to specific conventions such as types and naming conventions.

I want to emphasize that I am interested in testing the actual content of these files, not a modified version through Angular Mock's $httpBackend.

To make the JSON files accessible, I have configured them to be served in my karma.conf.js file.

files: [
  { pattern: 'static/assets/json/cards/*.json', included: false, served: true },
  'path/to/angular.js',
  'path/to/angular-mocks.js',
  'tests/**/*.js'
]

After initiating the command karma start, I can visit

/base/static/assets/json/cards/something.json
and confirm that the files are being served correctly.

Subsequently, in my test suite, I inject both the $http and $q services.

var $http, $q;

beforeEach(module('chai'));
beforeEach(inject(function(_$http_, _$q_) {
  $http = _$http_;
  $q = _$q_;
}));

My approach involves loading each resource using $http.get, gathering the promises returned from $http.get, then utilizing $q.all to ensure all promises are fulfilled before proceeding with the tests.

it('should load the resources', function(done) {
  var promises = ['admissions.json', 'discharge.json']
  .map(function(resource) {
    console.log('Loading', resource);
    return $http.get('/base/static/assets/json/cards/' + resource);
  });

  $q.all(promises)
  .then(function(card) {
    console.log('Success');
    done();
  }, function(err) {
    console.log('Failure', err);
    done();
  });
});

However, when I run my tests, I encounter the following error in the console:

Loading admissions.json
Loading discharge.json
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

Initially, I suspected that the time taken to load the files might be causing the timeout issue, but the size of the file is only 95kb.

Then I considered whether the custom promise interface (.success and .error) was disrupting the functioning of $q.all. However, this does not seem to be the case.

Finally, I attempted to send a standalone request for

/base/static/assets/json/cards/admissions.json
at the beginning of the tests. Despite receiving a promise as expected, it never resolves since there is no response sent back. Upon inspecting the network tools, I discovered that the request isn't even initiated. The code does run, but for some reason, $http fails to make the request.

My current assumption is that this could be related to Angular Mocks intercepting $http requests for its own $httpBackend service. How can I work around this obstacle?

Answer №1

I stumbled upon a helpful resource in this insightful blog post. One key takeaway is the importance of including the digest of the scope, even when not specifically testing controllers.

it('executes a certain task', function() {
    var result;
    deferred.promise.then(function(_result_) {
        result = _result_;
    });
    deferred.resolve(10);
    expect(result).not.toBe(10); // still pending as $digest has yet to run
    $scope.$digest();
    expect(result).toBe(10); // now 10 after running $digest
});

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

Save message in the callback function of the express app.listen method

I'm currently integrating winston logging into my application and aiming to switch all info or error level logs with winston's .info and .error. Everything seems to be working well except when trying to log an info message from within the app.lis ...

Placing a hyperlink within template strings

Currently, I am working on implementing a stylish email template for when a user registers with their email. To achieve this, I am utilizing Express and Node Mailer. Initially, my code appeared as follows: "Hello, " + user.username + ",&bs ...

"Mastering the Geocoder Class: Unleashing the Power of AJAX for Latitude and Longitude Retrie

This JSON array includes a collection of addresses [ { "id": 0, "title": "Coop.Sociale Prassi e Ricerca Onlus", "latitude": 0, "longitude": 0, "address": "Viale Eleonora D'Arborea 12, Roma, IT" }, { "id": 0, "title": "San Lorenzo", "lati ...

Exploring the concept of generator functions in ES6

I'm grappling with understanding JS generators and why the asynchronous operations in the example below are returning undefined. I thought that using yield was supposed to wait for asynchronous calls to finish. function getUsers(){ var users; $.aj ...

Accessing nested arrays and objects within JSON using Node.js

I'm in the process of developing an application that retrieves a JSON response from an API call using SONARQUBE. With node js, how can I extract the value of duplicated_lines from the following JSON object? I attempted the code below but it always r ...

How can you create a jQuery fade in effect for a single <li> element

I'm in the process of developing a task management app that generates a new li element every time a user adds an item. However, I am facing an issue where fadeIn() is activating for every li on the page whenever a new item is added. Does anyone have s ...

Angular library for creating stacked bar and line charts

Is there a specific AngularJS library that is able to create a chart with stacked bars and lines, similar to the one shown here: https://i.sstatic.net/V0WtM.png I am in search of a library that can handle this requirement using Angular directives. I came ...

Forward users to specific date and time on Everwebinar link

Is there a way to automatically redirect visitors of my custom Everwebinar confirmation page (on my domain) to a specific URL at a set date and time that is included in the confirmation page URL? Here is an example of what the confirmation page URL looks ...

Is it possible to use an angular expression as the ng-click function?

I have been searching everywhere for the answer to this question. Within my code, there is an angular object called column.addOnParams. This object includes a child element named rowClick, which can be accessed using column.addOnParams.rowClick. The val ...

Understanding the npm install command

I'm trying to understand how npm install actually functions. Shouldn't it have automatically installed all the dependencies listed in package.json? I visited the documentation npm install npm install (in package directory, no arguments): ...

When data is stored in Internet Explorer's cache, any changes made are not being reflected in

Internet Explorer stores data in cache and even if there are changes, it may not reflect onclick. However, when I open the developer mode and try to access the same, then it works perfectly. This issue only seems to occur in IE as all other browsers work f ...

Error encountered: Invalid symbol detected ('<') while attempting to parse JSON in an Angular application

I am experiencing an issue with my Angular code when trying to submit a form. Upon clicking the submit button, an error saying JSON Parse error: Unrecognized token '<' appears, and empty records are being saved in the database. I have included ...

The Angular currency filter is displaying a strange blank space despite the correct syntax being used. Is there anyone who can assist me with this issue?

Hey everyone, I'm having some trouble with the currency filter in Angular. It's not working and just displaying a blank space. I'm new to learning Angular so any help would be greatly appreciated! Here is the code I'm using: <!DOCT ...

Steps for adding a JSON object to an unordered list

After receiving data from a web server, I created a JSON object using the code obj = JSON.parse(data). This object contains information about dinosaurs such as their name, group, diet, and period. This is what the JSON object looks like: [{"name":"Stauri ...

Tips for automatically closing the Toggle Navigation feature in Vue JS when a user clicks outside of the navigation container

Is there a way to close the toggled navigation menu automatically when the user clicks outside of the navigation container? I have implemented two ul menus inside the navigation menu and would like the subNavActive, safNavAcitve, and repNavUl variables to ...

Various concatenated and compressed JavaScript files across multiple HTML documents within a single application

In my express.js application, I have different routes such as /home and /dashboard. For example, on the home page, I include: jquery.js, underscore.js, somemodule1.js, somemodule2.js. On the dashboard, I include: jquery.js, underscore.js, somemodule3.js, ...

The information retrieved from the database query is failing to appear on my webpage

I am encountering an issue where I am unable to display product details on my webpage in a specific format after submitting an ID number through a form. The query does not show any data when submitted. My objective is to append the latest retrieved data be ...

Electron Web Workers do not have compatibility with NodeJS modules

I'm currently working on a desktop application using Electron paired with ReactJS. From the initial renderer process, I create a hidden BrowserWindow to launch another renderer process. Within this new renderer process, I set up a web worker that wil ...

Can date ranges be utilized as separate date items on the time scale in D3.js?

I have a chart that resembles the one shown below, however, there is a crucial component missing. Currently, my time scale follows the standard format as depicted in the first picture. I am looking to convert it to the time scale seen in the second picture ...

Automatically scrolling through a nested list in ReactJs

I have a chat list integrated into my web application. The entire webpage is scrollable, as shown in the image at the bottom. I would like the messages list to automatically scroll to the bottom whenever a new message arrives. To achieve this, I created a ...