Testing the $resource function invoked by Karma Jasmine within a controller

I am facing challenges with implementing Karma to test API calls.

Below is the test file provided:

describe('Requests controller test', function() {
  beforeEach(module('balrogApp.requests'));

  var ctrl, scope;
  var requestData = [
    {id: 1, project: {id: 1, title: 'Project 1'}, description: 'Some description'},
    {id: 2, project: {id: 2, title: 'Project 2'}, description: 'Another description'}
  ];

  beforeEach(inject(function($rootScope, $controller, _$httpBackend_) {
    $httpBackend = _$httpBackend_;

    $httpBackend.expectGET('/users').respond(requestData);
    $httpBackend.expectGET('/requests').respond(requestData);
    $httpBackend.expectGET('/projects').respond(requestData);
    $httpBackend.expectGET('/requestcomments').respond(requestData);
    $httpBackend.expectGET('/costestimations').respond(requestData);
    $httpBackend.expectGET('/regions').respond(requestData);

    scope = $rootScope.$new();
    ctrl = $controller('requestsController', {$scope: scope});
  }));

  afterEach(function() {
    scope.$destroy();
  });

  it('should populate properties from xhr request results', function() {
    var unresolvedResponse = [];

    expect(ctrl.usersList).toEqual(unresolvedResponse);
    expect(ctrl.requestsList).toEqual(unresolvedResponse);
    expect(ctrl.projectsList).toEqual(unresolvedResponse);
    expect(ctrl.requestsCommentsList).toEqual(unresolvedResponse);
    expect(ctrl.costEstimationsList).toEqual(unresolvedResponse);
    expect(ctrl.regionsList).toEqual(unresolvedResponse);

    $httpBackend.flush();

    expect(ctrl.usersList).toEqual(requestData);
    expect(ctrl.requestsList).toEqual(requestData);
    expect(ctrl.projectsList).toEqual(requestData);
    expect(ctrl.requestsCommentsList).toEqual(requestData);
    expect(ctrl.costEstimationsList).toEqual(requestData);
    expect(ctrl.regionsList).toEqual(requestData);
  });
});

I attempted to use toBeUndefined() instead of toEqual(unresolvedResponse) with no success.

Below is the file where the $resource are defined:

angular.module('balrogApp.services', ['balrogApp.config', 'ngResource'])
  .factory('Requests', ['$resource', 'balrogConfig', function($resource, balrogConfig) {
    return $resource(balrogConfig.backend + '/requests/:id', {id: '@id'});
  }])
  .factory('Projects', ['$resource', 'balrogConfig', function($resource, balrogConfig) {
    return $resource(balrogConfig.backend + '/projects/:id', {id: '@id'}, {'update': { method:'PUT' }});
  }])
  /*  Other factories are there */
  .factory('CostEstimations', ['$resource', 'balrogConfig', function($resource, balrogConfig) {
    return $resource(balrogConfig.backend + '/costestimations/:id', {id: '@id'});
  }]);

Finally, here is a snippet of the controller file that is being tested:

angular.module('balrogApp.requests', [
  /* Dependencies */
])
  .controller('requestsController', function(Requests, Users, Projects, RequestsComments, CostEstimations,
                                             Regions, growl, $route, $rootScope, $scope, $location) {
    /* ... */

    this.usersList = Users.query();
    this.requestsList = Requests.query();
    this.projectsList = Projects.query();
    this.requestsCommentsList = RequestsComments.query();
    this.costEstimationsList = CostEstimations.query();
    this.regionsList = Regions.query();
  });

Currently, I am encountering the following error:

Expected [ $promise: Promise({ $$state: Object({ status: 0 }) }), $resolved: false ] to equal [  ].

I have tried setting unresolvedResponse to this value (with and without a proper syntax) but the issue persists.

Answer №1

When I tested it out myself, I discovered a new approach to handling the situation. Instead of using:

expect(ctrl.usersList).toEqual(unresolvedResponse);

try using

expect(ctrl.usersList.$resolved).toBeFalsy();

By making this simple change, you can confirm that the request has been made, the promise is in place, but no response has been received from the server yet.

I believe this trick will be beneficial to you in your testing.

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

Is it possible to configure route localization in Next.js and next-i18next to function as an URL alias?

Currently, I am utilizing NextJs version 10.0.5 in conjunction with next-i18next version 8.1.0 to localize my application. With the introduction of subpath routing for internationalized routing in NextJs 10, I encountered a situation where I needed to modi ...

The code "Grunt server" was not recognized as a valid command in the

I recently set up Grunt in my project directory with the following command: npm install grunt However, when I tried to run Grunt server in my project directory, it returned a "command not found" error. Raj$ grunt server -bash: grunt: command not found ...

Highlight the active menu item using jQuery

Check out my menu example here: http://jsfiddle.net/hu5x3hL1/3/ Here is the HTML code: <ul id="menu" class="sidebar"> <li> <a href="#" class="clickme">Menu</a> <ul id="menu1"> <li><a class="dropdown-clas ...

Tips for setting up a full-size image with nextJS and the <Image /> component

Upgrading NextJS to the latest version has resulted in some errors when using the Image component: // import Image from 'next/image' <div style={Object.assign({}, styles.slide, style)} key={key}> <Image src={src} alt="&quo ...

The perplexing configuration of a webpack/ES6 project

I am currently in the process of setting up my very first ES6 and webpack "application" where I aim to utilize classes and modules. However, each time I attempt to transpile the application using the webpack command, I encounter the following error: $ web ...

Learn the process of assigning a value to a dynamically created textbox using JavaScript in code behind

To create a textbox in the code behind, I use the following method: TextBox txt = new TextBox(); txt.ID = "txtRef" + count + dr["DataField"].ToString(); div.Controls.Add(txt); I have been attempting to set the value for this textbox within a jQuery funct ...

"Creating a duplicate of an element by utilizing the `next`

I have a dilemma involving two divs within a section of my project - one div is dynamically created while the other exists statically. My goal is to transfer the non-dynamically created div into the one that is generated dynamically. let adContainer = $ ...

Using async await in node.js allows you to bypass the need for a second await statement when

As I dive into using await async in my Node.js ES6 code... async insertIngot(body, callback) { console.log('*** ItemsRepository.insertIngot'); console.log(body); const data = await this.getItemsTest(); console.log('*** ge ...

Create a script that ensures my website can be set as the homepage on any internet browser

I am currently in search of a way to prompt users on my website to set it as their homepage. Upon clicking "Yes," I would like to execute a script that will automatically make my website the user's browser homepage. I have come across a Similar Thread ...

Unlocking Global Opportunities with Stencil for Internationalization

Hi there, I've been attempting to implement Internationalization in my stencil project but unfortunately, it's not working as expected. I'm not sure what's causing the issue, and all I'm seeing is a 404 error. I followed these arti ...

What is the best way to pass parameters to a PHP script using AJAX to ensure they are properly processed on the server side?

I'm working with the following function: function myFunction () { $.getJSON('remote.php', function(json) { var messages = json; function check() { ... In this function, I call the remote.php script which e ...

Auto language-switch on page load

Wondering if using jQuery is the best approach to create a single French page on my predominantly English website. I want it to work across multiple browsers on pageload, currently using HTML replace. jQuery(function($) { $("body").children().each(funct ...

Difficulty loading AngularJS 1.3 page on Internet Explorer 8

Being an avid user of Angular, it pains me to even bring up the topic of IE8, a browser that many consider to be pure evil and deserving of extinction. Despite my reservations, I am experiencing difficulties with loading Angular 1.3 in IE8. The page break ...

The jQuery fadeOut function modifies or erases the window hash

While troubleshooting my website, I discovered the following: /* SOME my-web.com/index/#hash HERE... */ me.slides.eq(me.curID).fadeOut(me.options.fade.interval, me.options.fade.easing, function(){ /* HERE HASH IS CLEARED: my-web.com/index/# * ...

retrieve information from a database using angularjs with the use of a specified condition

I am looking to retrieve data from a MySQL database using AngularJS. Here is how the application functions: Users log in and their username is stored in a cookie. This username is then displayed on the home page. The goal is to extract this value, pass i ...

Using Axios to retrieve data from a MySQL database is a common practice in web development. By integrating Vue

I have developed another Vue.js admin page specifically for "writer" where I can display post data fetched from a MySQL database. The admin page called "admin" is functioning properly and responding with all the necessary data. The following code snippet ...

Transform a group of objects in Typescript into a new object with a modified structure

Struggling to figure out how to modify the return value of reduce without resorting to clunky type assertions. Take this snippet for example: const list: Array<Record<string, string | number>> = [ { resourceName: "a", usage: ...

My Instagram stream using the Ionic framework's infinite-scroll feature is experiencing issues with repeated duplicates in the repeater

I am currently working on developing a mobile app for IOS and Android using the Ionic Framework. The app will feature an Instagram Feed with the Instagram API, displaying all photos shared under a specific hashtag (for example, #chocolat). I am also lookin ...

Ajax receives the entire webpage from php script

I am attempting to utilize AJAX to call a PHP function. The AJAX call is triggered from PHP with an onclick function in a button. However, instead of the value returned by the called function add_player, I am receiving the entire page exec.php. Thank you f ...

Running a Chrome content script once an AJAX request has been triggered by the <body> element

I am facing a challenge with running the content script before the DOM is fully loaded. To give context, there is an AJAX request within a tag which gets triggered on $(document).ready(). Once this request is completed, my extension code kicks in. To tra ...