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

Choose a subclass within a superclass by utilizing the "this" keyword

Whenever a user clicks on the class addMass, I want to add the attribute data-rate to the element with the class currentMass. Since there can be multiple elements with the class addToCart, I need to ensure that the changes are only applied to the one that ...

Leveraging the results from a static React function

I am currently working on a React + Webpack project that supports JavaScript ECMAScript 6. Here is the code snippet I am trying to implement: class ApiCalls extends React.Component{ static uploadFiles(files) { // upload code if(success) { ...

Angular Universal functioning fine on local host, yet encountering issues on Nginx Server

I recently developed a project with Angular Universal. After building the project, it generated files such as browser, server, server.js, and prerender.js. I am curious to learn how I can run this project on an nginx server. Currently, I create a build o ...

When both input fields share the same directive, scope.$eval() will be undefined

Looking for a way to validate two password input fields and ensure they are equal? (Open to alternative suggestions if my current method is incorrect) I created a directive with basic validation to compare the "confirm" password with the original one. How ...

Error Message: AngularJS Breeze - Property 'then' cannot be accessed on an undefined or null reference

I encountered a specific exception after retrieving data from the breeze controller. TypeError: Unable to get property 'then' of undefined or null reference Here is the code snippet involved: Student.js function fetchUsers() { return re ...

Determining when props are updated in Vue.js 2 when passing an object as a prop

Let's say there is an array feedsArray, with a sample value like this: this.feedsArray = [ { id: 1, type: 'Comment', value: 'How are you today ?' }, { id: 2, type: 'Meet', name: 'Daily ...

What are the best methods for preventing scss styles from leaking between pages?

I'm currently working on a project that includes the following files: /* styles/1.scss */ body { /* Some other styles not related to background-color */ } /* styles/2.scss */ body { background-color: blue; } // pages/one.js import "../styles/ ...

Steps for installing an npm package from a downloaded folder

In the past, I had a method of installing an npm project from Github that involved using git clone followed by npm install. git clone http...my_project npm install my_project Instead of manually copying the contents of my_project to my local node_modules ...

Issue with Angular failing to identify jQuery after transferring the dependency from package.json to bower.json

Initially, my project included angular, angular-bootstrap, and jquery in the package.json file, with everything being compiled using browserify. // package "dependencies": { "angular": "~1.4.6", "angular-bootstrap": "~0.12.2", "jquery": "~2.1. ...

The AngularJS $HTTP loop counter fails to update

When working with an HTTP service and binding JSON data to HTML, I implemented the following code: This function uses a 2-second timer to automatically fetch data whenever there is a change in the backend. function sampleDevices ...

I am struggling to display the data fetched by Next.js on the page

I am struggling to display the data from the first file in my tanstack table or as a string within the HTML, even though I can see it in a console.log when grabbed by axios. The tanstack table worked fine with hardcoded data. In the console image provided, ...

Harness the power of electrons with the simple push of a button - initiating program execution

Recently, I delved into Electron with the desire to create a small application for myself. This app would allow me to run different programs or games by simply clicking on a link. My goal is to have the program/game start automatically when I open the Ele ...

What is the method for retrieving the locale value from the configuration in Next.js?

How can I retrieve the i18n.defaultLocale value from my Next.js app configuration? I thought it would be simple, but I'm struggling to find a clear solution for accessing the config settings in Next.js. Is there a specific built-in method for this, or ...

Which is quicker: loading JSON via Ajax or loading the entire output through Ajax?

I'm interested in gathering different perspectives on this topic. Currently, I have Jquery initiating a function through ajax which loads data in two ways: The ajax script fetches JSON data from the server itself, then utilizes JavaScript to pars ...

Organizing layers with Leaflet's layerGroup controls

I am working with a series of Leaflet FeatureGroups, each made up of GeoJSON layers. These FeatureGroups have similar concepts but need to be kept separate for control purposes. I also require the ability to toggle all FeatureGroups on and off simultaneous ...

Installation Failure: Angular-CLI/Chokidents Partnership Error

Newest Node version is 6.7.0 Encountered an error during installation stating notsup not supported by this operating system Operating System: Windows 10 ...

Sending product identification to content_ids for Facebook Pixel tracking

Looking to implement Facebook Pixel for tracking the ViewContent event on product pages. According to Facebook, it's necessary to provide content_ids or contents along with a content_type. I assume that the content_type should always be 'product ...

Exploring the connections among nodes in a Force-Directed Graph using D3.js JavaScript

I am currently working on a complex graph that consists of around 150 nodes using D3 Javascript. The concept behind it is quite intriguing: Each node is interconnected with 100 other nodes. Out of these 100 nodes, 49 are further linked to another set of ...

Searching for Bluetooth devices using React Native

In my project, I am working on scanning HM-10 BLE with a react-native app. To achieve this, I referred to the example provided in Scanning for Bluetooth devices with React Native. So far, the library seems to be successfully installed without any errors du ...

Identifying duplicate values in an array of objects using JavaScript

I am facing an issue with my array that collects data from a spreadsheet into studentCCAList. Sometimes, a student may have multiple subjects. For example, Name: Joseph Subject: English Name: Peter Math Name: Joseph Subject: Science My concern i ...