Troubleshooting unit tests within my application

I am encountering an issue with loading a $resource object in my current scenario.

In the parent controller, I have defined:

$scope.data = Product.$query();

Then, in the child controller:

$scope.data.$promise.then(function(product){
     console.log(data);
})

This is how my factory looks like:

angular.module('testApp').factory('Product', ['$resource', function ($resource) {
    return $resource('/api/product');
}]);

The reason for placing Product.$query() in the parent controller is to share it and use it across different child controllers.

My test file setup includes:

describe('Product test ', function () {
    var $httpBackend, childCtrl,  scope;

    beforeEach(module('testApp', function($provide) {
        $provide.value('$log', console);
    }));

    beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_) {
        scope = _$rootScope_.$new();
        $rootScope = _$rootScope_;
        $httpBackend = _$httpBackend_;

        childCtrl = _$controller_('childCtrl', {
            $scope: scope
        });
    }));

    describe('some test', function() {
        it('some test here', function(){
             //codes...
        })
    })
});

However, when running the test, I encounter the error:

TypeError: 'undefined' is not an object (evaluating '$scope.data.$promise')

I am unsure about what might be causing this. Any assistance would be greatly appreciated. Thank you.

Answer №1

When testing the $resource object in jasmine, it is important to create a mock response using $httpBackend. This mock response will be returned when querying the $resource, instead of directly using `$resource`.

describe('Product test ', function () {
    var $httpBackend, childCtrl,  scope, Product;

    beforeEach(module('testApp', function($provide) {
        $provide.value('$log', console);
    }));

    beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_, Product) {
        scope = _$rootScope_.$new();
        $rootScope = _$rootScope_;
        $httpBackend = _$httpBackend_;
        Product = Product;

        childCtrl = _$controller_('childCtrl', {
            $scope: scope,
            Product: Product
        });
    }));

    describe('some test', function() {
        it('some test here', function(){
             $httpBackend.expect('GET', '/api/product').respond([{ id: 1, name: 'a' }, { id: 2, name: 'b' }]);
             childCtrl.data = Product.query();
                 expect(childCtrl.projects).toEqualData([]);
                 $httpBackend.flush(); //flushing $httpBackend
                 expect(childCtrl.data).toEqualData([{ id: 1, name: 'a' }, { id: 2, name: 'b' }]);
        })
    })
});

For more information on this topic, please visit this link

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

Receive alerts from flash document within html

I have a flash file embedded in an html document using the embed tag. I am looking for a way to trigger a JavaScript action, such as an alert, once the Flash content has finished playing. Is there a method to achieve this? ...

Modify the parent div's background color on mouseover of the child li

I want to update the background image of a parent div that contains a series of ul li elements. Here is the HTML code I am working with: <section class="list" id="services"> <div class="row"> <ul> <li>& ...

Ways to verify if TypeScript declaration files successfully compile with local JavaScript library

I have recently updated the typescript definitions in HunterLarco/twitter-v2, which now follows this structure: package.json src/ twitter.js twitter.d.ts Credentials.js Credentials.d.ts My goal is to verify that the .js files correspond correctly ...

Updating view in AngularJS using Promises

I am currently facing an issue where I need to update the view of an Angular application from its controller using an ES6 Promise (fetch) resolved value. The challenge lies in the fact that Angular does not automatically update the view when my promise res ...

utilize the useRef hook to display the total number of characters within a text area

Introducing the following component: import React from 'react'; export interface TexareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> { maxLength?: number; id: string; } export const Textarea = React.forwardRef( ( ...

Issue with bootstrap tooltip visibility within a specific div container

I am trying to align a div tag to the right, but when I add a Bootstrap tooltip to the left of it, the tooltip is not appearing. <div class="container-fluid"> <div class="row"> <div id="map" style="width: 100%; height ...

Angular will hold off until the subscribe operation has completed before passing values to another function

Here's a function I have in the code: File: subcategory.service.ts getSubCategoriesById(inp_subCatid: String): Observable<any>{ this.getSubCategoriesList().snapshotChanges().pipe( map(changes => changes.map(c => ({ key: ...

Discover a method to receive an alert when the mouse exits the inner window along the y-axis

Is there a way to receive an alert if the mouse moves out of the inner window solely in the y-axis? Currently, alerts are triggered when the mouse moves out on both x-axis and y-axis. For example, if the mouse pointer hovers over the address bar coming fro ...

Is it possible for Angular.js timer finish event not to trigger data binding correctly?

I've been working on an AngularJS application that functions as a quiz by displaying pictures and prompting users to select the correct answer by clicking a button. The app is designed to store the user's answers in an object. Everything seems t ...

javascript challenge with inheritance

I am encountering an issue with two objects where one inherits from the other. The parent object is sending an ajax request to send some contact email. However, when I use the child object to send the request, all data is empty for some reason. The ajax r ...

Encountering issues while trying to duplicate react-table CodeSandbox: API error when using localhost

Trying to implement this CodeSandbox project into my own project has been challenging. On navigating to the Example component, a 404 error pops up: Error: Request failed with status code 404. The API is targeting this endpoint: http://localhost:3000/api/pr ...

The filter designed for rearranging elements will not function

let wrap = document.querySelector(".wrap"); let temp = document.querySelector(".temp"); temp.addEventListener("click", (event) => { // grabs the first paragraph child element, which is working correctly console.log(wrap.children[0].firstElementChild ...

What could be the reason my div is not being hidden in jQuery?

Creating a quiz layout for school is my current project, and I'm just getting started. My goal is to have the questions disappear once the 'next question' button is clicked. The issue arises after the second question because instead of the ...

Updating a URL for all users using React/Next.js and Firebase: a guide to refreshing the page

I am currently developing a Next.js application with a Firebase backend and have encountered an issue. In my setup, users can create sessions that others can join, but only the creator of the session can "start" it, triggering a state change. I need all us ...

Tips for successfully executing child_process.exec within an ajax request

On a server that I have access to but not ownership of, there is a node js / express application running on port 3000. Various scripts are typically executed manually from the terminal or via cron job. My goal is to have a button on the client-side that tr ...

showing data from a multidimensional array in an Angular UI grid widget

After receiving the data structure array from an API, I am faced with the task of displaying nested array properties for each record. Here is the approach I am currently taking: $scope.gridOptions = {}; $scope.gridOptions.columnDefs = []; $sco ...

Determine the position of a nested object within a multidimensional array using JavaScript/TypeScript

My objective is to obtain the complete index of a complex object within a multidimensional array. For example, consider the following array: var arr = [ { name: "zero", children: null }, { name: "one", children: [ { ...

Challenges integrating Jquery with Flask

When attempting to add an HTML element using jQuery, I encountered an exception from Flask: jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'static' The string seems correct, but I'm unsure about what the issue ...

CSS and JavaScript Nav Menu Collapse (No Bootstrap)

I have written a navbar code using pure HTML/SASS, but I am facing a challenge in adding a collapse element to the navigation bar. Despite trying various solutions from Stack Overflow, I still haven't found one that works for me. Therefore, I am rea ...

Modify select option in Bootstrap Vue based on user input

I am facing a challenge in populating a Bootstrap-Vue form select with objects obtained via JSON. The JSON data comprises teacher information from various fields: [ { "id": 1, "name": "John", "surname": ...