Experiencing [$resource:badcfg] error in Angular JS while testing $resource.get function, yet no issues when used in the controller

My Article resource is set up like this:

define(['services/index', 'services/Helpers'], function(services) {
  'use strict';

  services.factory('Article', ['$http', '$resource', 'AppConfig',
    function($http, $resource, AppConfig) {
      return $resource('http://' + AppConfig.APIHost + '/api/v1/articles/:id.:format', {id: '@id', format: 'json'});
    }
  ]);

});

When I use the resource in a controller, everything works fine. But during unit testing with code similar to this:

define(
  [
    'app',
    'services/Article',
    'mocks/articles'
  ],
  function() {
    describe('Service: Article', function () {

      // load the service's module
      beforeEach(module('ngResource', 'services', 'mocks'));
      beforeEach(function() {
        this.addMatchers({
          toEqualData: function(expected) {
            return angular.equals(this.actual, expected);
          }
        });
      });

      // instantiate service
      var Article, $httpBackend, injector, mockValues = {};

      beforeEach(inject(function(_Article_, _$injector_) {
        Article = _Article_;
        injector = _$injector_;

        $httpBackend  = injector.get('$httpBackend');
        mockValues.articlesMocksSet   = injector.get('articlesMocksSet');
        mockValues.articlesSuccessful = injector.get('articlesSuccessful');

        $httpBackend.whenGET(mockValues.articlesMocksSet.urlRegex)
          .respond(mockValues.articlesSuccessful);
      }));

      it('should be able to query from the API', function() {
        var articles;
        Article.query(function(results) {
          articles = results;
        });
        $httpBackend.flush();
        expect(articles).toEqualData(mockValues.articlesSuccessful);
      });

      // Temporarily pending due to a bug in Angular v1.0.8
      it('should be able to query individual article by id', function() {
        mockValues.getArticleMocksSet   = injector.get('getArticleMocksSet');
        mockValues.getArticleSuccessful = injector.get('getArticleSuccessful');

        $httpBackend.whenGET(mockValues.getArticleMocksSet.urlRegex)
          .respond(mockValues.getArticleSuccessful);

        var article;
        Article.get({id: mockValues.getArticleMocksSet.id}, function(result) {
          article = result;
        });
        $httpBackend.flush();
        expect(article).toEqualData(mockValues.getArticleSuccessful);
      })
    });
  }
);

The error I encounter is:

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an object but got an array
  http://errors.angularjs.org/1.2.0/$resource/badcfg?p0=object&p1=array

I have double-checked the resource configuration and confirmed that the JSON object is not an array. What could I be missing?

Answer №1

After realizing that the $httpBackend mock order was incorrect, I discovered the following:

$httpBackend.whenGET(mockValues.articlesMocksSet.urlRegex)
  .respond(mockValues.articlesSuccessful);

$httpBackend.whenGET(mockValues.getArticleMocksSet.urlRegex)
  .respond(mockValues.getArticleSuccessful);

Therefore, the correct order should be /api\/v1\/articles/ followed by /api\/v1\/articles\/[\w|-]*/. Reversing this order resulted in receiving an array response rather than an object.

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

405 Method Not Allowed - Compatible with all devices except for iOS Safari

Recently, I've been working on an application using AngularJS to track and submit statistics to a Google Apps Script for processing. While everything functions flawlessly on my computer in both Chrome and Firefox, encountering errors on the iPad has b ...

What is the best way to manage a string containing quotes?

Currently, I have a JavaScript function that is being called using the following code: <a href='javascript:void(0)' onclick='javascript:onEditRevPrepare(" <%#Convert.ToString(Eval("ReviewTitle"))%>"> The issue arises when th ...

Combine two elements together and display the outcome in json form

There are two objects that need to be summed up and returned in the same format as the original objects stored in a local file. The first JSON: { "data": [{ "x": "Q1 (J, F, M)", "y": [100, 500, 0], "tooltip": "this is tooltip" }, { "x": "Q2(A, M, ...

Embarking on the Protractor, Travis, and SauceLabs journey

Currently, I am in the process of setting up my open source project tests on Travis CI. I have successfully run them locally using a Selenium server. Although it seems like a straightforward task, I find myself lacking some basic knowledge to finalize the ...

Quantities with decimal points and units can be either negative or positive

I need a specialized input field that only accepts negative or positive values with decimals, followed by predefined units stored in an array. Examples of accepted values include: var inputValue = "150px"; <---- This could be anything (from the input) ...

Embracing the beauty of incorporating nested quotations

I've been experimenting with jquery's append functions lately. I'm adding a substantial amount of html, specifically a button with an onclick event function. It might sound complicated, but due to some technical restrictions, this is my onl ...

Cross-Domain Communication with XMLHttpRequest

I am facing an issue with the code snippet below: console.log(1); var xhr = new XMLHttpRequest(); xhr.open('POST', 'http://anothersite.com/deal-with-data.php'); xhr.setRequestHeader('Content-typ ...

Creating components in React with CSS styling

After developing a component using React, I managed to use Babel to build it into the lib directory successfully. However, when it comes to building my CSS, I find myself at a loss and in need of assistance. Any help would be greatly appreciated. Thank yo ...

Integrate new functionality into the plugin's JavaScript code without directly editing the JS file

I need to incorporate a new function called 'setInputDataId' at the same level as the existing function '_select' in the plugin js file without directly modifying the file itself. I am seeking guidance on how to add this new function. ...

Looking to store HTML form data in MongoDB and showcase the saved information on a webpage using AngularJS, ExpressJS, and NodeJS

Client-side : Example HTML Code <body ng-controller="myAppController"> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <h1>person details</h1> </div> ...

What is the proper way to perform date validation using the moment library in JavaScript?

I am facing an issue with the departure date validation on my website. I have a textbox called txtDepartureDate where users can choose the date of departure. The requirement is that if the selected date is before today's date, an error message should ...

Change the icon switch from fas fa-lock-open to fas fa-lock by adding an event listener for a click action

let lockIcon = document.createElement("i"); lockIcon.setAttribute("class", "fas fa-lock-open"); lockIcon.setAttribute("id", color + "lock"); Is there a way to toggle between the icons fas fa-lock-open and fas fa-lock when clicking using a ...

Configuring CORS in an Angular JS controller

Having a controller with a service that retrieves JSON from another server, I encountered the following issue: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:somesite.com. This can be fixed by moving the ...

Tips for sending JSON information to refresh Highcharts Pie chart

Currently, I am attempting to utilize AJAX to send a year value to my server. The server will then retrieve information from a database regarding various countries' economies for that specific year. Subsequently, I intend to use this data to update th ...

Using ThreeJS in conjunction with NextJS requires that class constructors be called with the 'new' keyword

Seeking assistance with rendering a basic scene within a nextJS route named "lab2". Encountering the following error: Error: class constructors must be invoked with 'new' Call Stack: renderWithHooks mountIndeterminateComponent ...

Bringing tex2max.js into an angular application using npm and index.html

Every time I attempt to import tex2max with the command declare var tex2max: any;, I encounter a ReferenceError: tex2max is not defined. Interestingly, this issue does not arise with other npm packages. Despite trying various methods such as installing the ...

Can you explain the significance of the CssClass property's value?

StyleClass="checkrequired[validate,funcCall[dateCheck]]" This special attribute is used in conjunction with an <asp:TextBox>. The webpage also includes a JavaScript function called dateCheck. I am uncertain whether this feature is part of ASP.NET or ...

Personalize product image

Currently, I am involved in a project that involves the creation of custom trading cards for clients. However, I am facing difficulty in finding a way to overlay the card template so that users can upload their photos into a specified box. Various methods ...

Step-by-step guide on building a personalized rxjs operator using destructured parameters

I am in the process of developing a unique RxJS filter operator that requires a destructured array as a parameter. Unfortunately, TypeScript seems to be throwing an error related to the type declaration: Error TS2493: Tuple type '[]' with a len ...

What advantages does using immutablejs offer compared to using object.freeze?

I've scoured the internet trying to find convincing reasons for using immutablejs instead of Object.freeze(), but I still haven't found a satisfactory answer! What are the advantages of working with non-native data structures in this library ove ...