Angular Testing - issue with promise returning unexpected results

I'm having trouble with populating vm.chartData in my HomeCtrl. Even though I've mocked data to it in the beforeEach() function, when I console.log(scope.vm.chartData), it returns undefined. However, other scope variables like graphLoading are properly defined and changed.

describe('HomeCtrl', function () {
    var controller, scope, myService, q, $timeout;

    beforeEach(module('dashboardApp'));

    beforeEach(inject(function ($controller, $rootScope, $q, _$timeout_) {
        controller = $controller;
        scope = $rootScope.$new();
        $timeout = _$timeout_;
        myService = jasmine.createSpyObj('Chart', ['get']);
        q = $q;
    }));


    describe('when returning promises', function () {

        beforeEach(function () {

            myService.get.and.returnValue(q.when( { result:
                'Stuff'
                }));

            controller('HomeCtrl as vm', { $scope: scope, Chart: myService });
            scope.$apply();

        });

        it('test dirty graph init', function () {
            expect(scope.vm.graphLoading).toBe(true);

            scope.vm.dirtyTestGraph();
            scope.$digest();
            $timeout.flush();

            expect(scope.vm.graphLoading).toBe(false);
            console.log(scope.vm.chartData);
        });
    });
});

relevant code from homectrl

vm.dirtyTestGraph = function() {
    vm.graphTitle = 'Deposit Amount';
    $timeout(function(){
        Chart.get( { interval:'3h', type:'_type:deposit',
                from:1416960000000, to:Date.now() } )
        .then(function(chart){
            vm.graphLoading = false;
            vm.chartData = chart.data;
        });
    }, 2000);
};

and here is the return value of Chart.get in the Chart factory

        return $q.all([chartData])
            .then(function(data){
                var graphData = data[0].data.facets[0].entries;
                var newData = [];
                graphData.forEach(function(element){
                    var newElem = {
                        time: element.time,
                        deposits: element.total.toFixed(2)
                    };
                    newData.push(newElem);
                });
                return new Chart(newData);
            });

Answer №1

The code in your controller is searching for a data property within the object returned by the promise from Chart.get:

vm.chartData = chart.data;

However, the stub in your test is providing an object that does not have a data property:

myService.get.and.returnValue(q.when({
    result: 'Stuff'
}));

Due to this, vm.chartData ends up being assigned as undefined.

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

Resetting the randomness in a function within a sudoku generator implemented in JavaScript

I'm in the process of creating a unique Sudoku generator that incorporates randomness into its design. Within my code, there's a particular function responsible for generating the Sudoku puzzles. The issue I'm encountering is the inability t ...

Having trouble resolving all parameters for AuthService in Angular

Launching my angular app has hit a roadblock with this perplexing error. Despite attempts to troubleshoot by removing the auth service provider and constructor reference from my component, the issue persists. As a novice in angular, I'm struggling to ...

What is the best approach for incorporating sub-navigation within a page popup in a Next.js project?

In the midst of my Next.js project, there is a requirement to showcase a chat popup consisting of multiple sub-pages like user registration, conversation page, and more. Hence, seamless navigation inside this popup is necessary. The idea is not to alter th ...

Error detected (unresolved promise): Invalid JSON format is causing an Unexpected token < at the beginning of data position (Application built with React/Redux)

I'm in the process of setting up user authentication using JWT. I've successfully created an API for this purpose. Now, my goal is to integrate this authentication API with my React/Redux App. When a user signs up, I trigger an action from my S ...

Implementing Dynamic Styling Using Parent Component in React Native

I am facing an issue with a <Text> component that is receiving a style through props... TextFile.js: <Text style={styles.text}> This is a line of text and this might be a second line </Text> screenFile.js: <View style={styles.v ...

What could be the reason behind the occurrence of an error after deleting certain lines of code

The code below is functioning correctly. obj = { go: function() { alert(this) } } obj.go(); // object (obj.go)(); // object (a = obj.go)(); // window (0 || obj.go)(); // window However, an error arises when I comment out the first two lines. obj ...

What is the best method to make an email address distinct?

<body> <p>Please input your email address:</p> <input id="email" style="margin-bottom: 20px; margin-top: 2px;" type="email" placeholder="Email Address"> <input onclick= "validateEmail(email)" type="su ...

Tips for passing down props or all the properties of an object to create a dynamic component

I am facing an issue with a v-for loop in my project. The loop is supposed to iterate through objects in a list of todos fetched from the backend. These objects are then passed down to a child component, which displays each todo individually. However, I ha ...

How can I efficiently locate identical sequences of cells in two or more arrays?

Unique Example 1 We can explore an interesting scenario by considering two arrays: ('m','o','o','n','s','t','a','r','d') ('s','t','a', ...

Interacting with jQuery UI Droppable by setting acceptance criteria before submitting a form

My goal is to create a draggable item that can be dropped onto a specific zone. The challenge I'm facing is in displaying a form for inputting information and storing it in a database. If the input is successfully stored, the drop action will be succe ...

The Laravel Ajax Request is Returning Null

I am faced with a perplexing issue involving a toggle button that should change the status (Show/Hide). Despite sending valid data via ajax and seeing correct data in the console, the request appears empty in the controller. I've made sure to include ...

Tips for accessing a web service using JavaScript (AJAX)

I have two projects: one is a web service and the other is an ASP.NET web project. I am trying to insert data using JSON (with AJAX). I tested the web service file with code behind and it works fine, but I'm encountering an error with the JavaScript ...

What is the best way to manage files in Vue.js?

I am faced with a challenge in storing image files and video files as Blob data. One thing I like is that the uploaded video and image files display instantly, which is pretty cool. I'm not entirely sure if the code below is correct - how can I navi ...

What is the process of sending an HTTP/HTTPS request from a Node.js server?

Currently diving into the world of Node.js, I am experimenting with using a Node.js Application on cPanel to generate a JSON response upon accessing its URL. Upon visiting the app's URL, it seems that the Node.js server is functioning correctly. Afte ...

I am interested in having the push notification feature function specifically for registered users

In an attempt to register the device for push notification using the PhoneGap plugin, I am encountering an issue. After the AJAX success action is called, the registration action does not alert the registration ID. Can someone help figure out what's g ...

Having difficulty applying a style to the <md-app-content> component in Vue

Having trouble applying the CSS property overflow:hidden to <md-app-content>...</md-app-content>. This is the section of code causing issues: <md-app-content id="main-containter-krishna" md-tag="div"> <Visualiser /> </md-app ...

Opening a document with `document.open` will clear all event listeners

I've developed a Chrome extension that records user behavior while browsing web pages by adding event listeners to customers' web pages using a Chrome content script. The code in the content script looks something like this: var recordingEvents ...

Is it possible to include a component in an HTML file when the constructor of the component needs a parameter?

Recently delving into the world of AngularJs has been a captivating experience for me. I am aiming to develop a component with a constructor that accepts a parameter of type string. However, when I try to declare the selector on the HTML file, the componen ...

Steps for deploying Nuxt on a subdirectory using either Express JS or Plesk

I have configured my Nuxt (Node.js application) to run on Plesk. This means that Plesk will execute the server.js file, which in turn runs ExpressJS and then Nuxt. Here is the content of my server.js file: const express = require('express') cons ...

Displaying fresh data from a JSON URL by clicking on a button and dynamically refreshing the view in

Apologies if this question has been asked before, but I couldn't locate it. I’m currently engaged in an Angular project where I’ve loaded an external JSON file using http. The data is presented through ngRepeat. When a button is clicked, I aim t ...