The value is undefined until a new Resource object is pushed with the item

I've encountered an issue while testing a factory and I can't seem to find anyone else with the same problem. Can someone help me figure out what's causing this strange error?

TypeError: 'undefined' is not a function (evaluating 'value.push(new Resource(item))')

Running angularjs v1.3.20

factory.js

'use strict';

//This service communicates with the articles REST endpoints for businesses
angular.module('businesses').factory('Business', ['$resource',
    function ($resource) {
        return $resource('api/businesses/:businessId', {
            businessId: '@_id'
        }, {
            update: {
                method: 'PUT'
            }
        });
    }
]);

test.js

describe('My Service', function () {


    //First, load the main application module
    beforeEach(module(ApplicationConfiguration.applicationModuleName));

    afterEach(inject(function($httpBackend){
        //Verify all expected http calls were made at the end of the test
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    }));

    it('mock http call', inject(function($httpBackend, Business) {
        var resource = new Business({
            _id:'abcd'
        });
        var arraya = [{
            _id:'abcd'
        }, {
            _id:'abcde'
        }];
        //Set expectation for correct url and respond with mock object
        $httpBackend.expectGET('api/businesses/abcd').respond(200, arraya)

        resource.$query();

        //Flush the request to mimic async action
        $httpBackend.flush();

        //Check if resource behaves as expected
        console.log(resource);
        //expect(resource.name).toBe('test');
    }));

});

xxxxxxxxxxxxxxxxxxxxxxxxxxx

Answer №1

Is it necessary to wait until after you've flushed before expecting something?

resource.$query();

//When simulating an asynchronous action, ngMock allows us to manually flush the request
$httpBackend.flush();

//Set an expectation for the correct URL and respond with a mock object
$httpBackend.expectGET('api/businesses/abcd').respond(200, arraya);

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

Activate the next tab by clicking a button in ReactJS

I currently have a web page with 4 tabs, each containing different sets of data. Within the first tab, I have a button that should activate the next tab's content when clicked by the user. render(){ return ( <MuiThemeProvider> ...

What is the best method to obtain the following id for an image?

Whenever I hover over the li with the number 3, I am getting the wrong number for the next id in the img tag. The first time, I get next id = 4 which is incorrect. But on the second hover, I get next id = 0 which is what I actually need. How can I correctl ...

JQuery jqx validation is experiencing some issues

Utilizing jquery plugins and widgets from jqx for basic form validation in my ruby-on-rails application has proven to be very helpful. Here is a simple example of an HTML form: <form id="newForm"> <input type="text" id="name"/> < ...

Issue with scrolling feature in div

I am currently facing an issue with scrolling on my website. Visit this site to see the problem. When scrolling down, it causes the "hidden" part of the site to slide up. I want to achieve a similar sliding effect, but it needs to be smooth. I have attempt ...

Leverage AJAX to fetch data from the database

I've been exploring different methods to automate the process of copying a database table. While replication was suggested as an option, I found it challenging to set up properly. Therefore, I have decided to use a script approach instead. In an effo ...

conducting a search through a list generated by a directive

As a newcomer to AngularJs, I have managed to create a directive that binds data from the controller to the HTML. Now, my goal is to implement a search functionality for the list displayed in AngularJs. This list consists of various objects. You can find t ...

Using the append() method in d3 with a function argument adds new

This is functional code: // A d3.select("body").selectAll(".testDiv") .data(["div1", "div2", "div3"]) .enter().append("div") .classed("testDiv", true) .text(function(d) { return d; }); The next snippet is essentially the same, except that ins ...

Canceling a promise in a Vuex action

I am looking to implement the ability to cancel a running promise in my Vue component, specifically a promise returned by a Vuex action. In my scenario, the Vuex action is continuously polling an endpoint for status updates, and I need the capability to s ...

The alert function is not being triggered upon receiving a JSON response

I am having trouble with an alert not firing a json response. The response appears in firebug, but after upgrading from php4.4.7 to php5.3.5, I encountered this error. It could be my mistake as well. Could someone please review my code and point out where ...

Is handlebars.js giving you trouble all of a sudden?

My handlebars.js template was working perfectly for a week, but suddenly stopped. I'm puzzled by this issue and would appreciate any insights on why it might have stopped functioning. Here is the template: <script id="banners-template" type=" ...

The constricted styles are causing the whole page to bounce (scroll) up and down

On my SPA frontend, I have a parent div with a height of 580 containing 9 smaller divs (about 190px in height each). The parent div has an overflow set to hidden so that only 3 elements are visible at one time. Every 5 seconds, I change the styles by addin ...

Storing a dynamically created grid of inputs using a consistent ng-model

I have the following code snippets: $scope.createPack = function(informationsPack, informationsActivite) { PackService.add(informationsPack, informationsActivite) .then(function(res) { $state.go(&apos ...

Display an error message when the button is clicked and the input field is left empty in a Vue 3 script setup

Hello, I am currently exploring Vue 3 and embarking on a new Vue 3 project venture. However, I seem to be encountering a challenge when it comes to displaying an error message if the button is clicked while the input field remains empty in my Vue 3 script ...

An issue with Axios request in a cordova app using a signed version

Currently, I am in the process of developing a Cordova application utilizing Axios and React. The interesting part is that everything runs smoothly when I build the app with Cordova and test it on my phone using the APK. However, once I sign, zipalign it, ...

Using the Coinbase.com API with HMAC authentication in a Node.js environment

I recently delved into some node.js documentation, specifically crypto and https, in an attempt to utilize the coinbase.com API within my coin.js file to retrieve the bitcoin balance of my account. However, I am encountering errors. Upon running the code w ...

AngularJS - Managing Multiple State Parameters

Currently, we are in the process of learning AngularJS and are facing difficulty with a specific issue. We aim to select a product type and utilize the formData value ("productType":"1") image1 to accurately display the JSON product data associated with th ...

What is the process for transferring information from a Ruby controller to an application JavaScript using AJAX?

When clicking a button, an AJAX call is made in my application.js file. It sends 3 data points to the events_controller#check action: //application.js $(document).on('click', "#check-button", function(){ ... $.ajax({ ...

Navigating Paths in Real-time with Javascript - Node.js

When working with PHP, dynamic routing can be achieved by defining classes and methods like: class Route { public function homePage () { echo 'You are on the home page' } public function otherPage () { echo 'You are on so ...

Failure to properly declare custom service

I recently started learning Angular.js and I hit a roadblock while trying to create a custom service. I followed the tutorial available at https://docs.angularjs.org/tutorial. Here is my app.js: var myApp = angular.module('myApp', [ 'ngR ...

transform the binary information into legible text

ETCD dashboard displays a binary string as shown below: var _deps_js = "\x1f\x8b\x08\x00\x00\x09\x6e\x88\x00\xff\xcc\xbd\x7b\x77\xdb\x46\xb2\x2f\xfa\xff&bs ...