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

The issue with triggering button events in JavaScript

I've integrated a jquery modal popup for saving uploaded files related to a specific device. The modal appears, the cancel button functions correctly, but I am struggling to trigger the onclick event for the Save button... This is what I have impleme ...

Retrieve a Vue Component by utilizing a personalized rendering method for a Contentful embedded entry

Currently experimenting with Contentful, encountering some issues with the Rich text content field. To customize the rendering of this block and incorporate assets and linked references in Rich text content, I am utilizing the modules '@contentful/ri ...

"Exploring the power of asynchronous programming with dynamic async await in

I am currently working on creating a versatile function that can dynamically call async functions. //passing the controller and functionName (string) function asyncAwaitCaller(controller, functionName) { let result = await controller[functionName]; } ...

Is it possible to modify state prior to the link being activated in react-router-dom?

I need to gather user information before the link works, but I'm not sure how to do that. The issue is that when I click on the link, the component it's linking to gets activated first without receiving the necessary info. const [userId, setUse ...

What is the best way to include extra parameters when using Upload.upload in AngularJS?

I'm facing an issue with uploading a file using AngularJS var requestData = { url: "/file_upload", data: {"name":"jack", file:file}, }; Upload.upload(requestData); This is the code in my controller. app.post("/file_upload", functio ...

Capturing information within a jQuery function by accessing data from another function

Can data be collected from another function while the function is running? // Custom Function function getData(){ var name = 'tom'; return name } // Main Target Area $('.myDiv').click(function(){ // I need to retrieve dat ...

Immediately Invoked Function Expression in Javascript

const user = { name: "John", age: 30, lastName: "Smith" } (({name, lastName}) => { console.log(name); console.log(lastName); })(user); An error occurred: {(intermediate value)(intermediate value)(intermediate value)} is not function ...

Using jQuery to display a div after a 2-second delay on my website, ensuring it only appears once and does not reappear when the page is refreshed or when navigating to a

I manage a website that includes a blog section. Every time someone visits the site, I want a popup window to appear. (To achieve this, follow these steps - Utilize jQuery for showing a div in 5 seconds) I would like this popup to only be displayed once ...

Unable to delete element from the given array

I have been working on removing instances of 'store.state.location.locations' from my locationData array that should no longer be there, but for some reason, they are persisting in the array even though I am no longer passing those instances. ta ...

I'm struggling to grasp the concept of State in React.js

Even though I'm trying my best, I am encountering an issue with obtaining JSON from an API. The following error is being thrown: TypeError: Cannot read property 'setState' of undefined(…) const Main = React.createClass({ getInitia ...

Identifying the length of a division element following its addition

I'm facing difficulties in detecting the length and index of the dynamically appended div. I have researched extensively and found a solution involving MutationObservers, but I am unsure if it is necessary for this particular issue. Let's focus ...

Is there a way to display the input value from an on-screen keyboard in an Angular application?

I have included my code and output snippet below. Is there a better way to display the input value when clicking on the virtual keyboard? ...

Having trouble sending data from AJAX to PHP

My goal is to implement a "load more" feature in my web app that automatically calls a PHP file to load additional products as soon as the page is fully loaded. In order to achieve this, I am using AJAX to call the PHP file: $(document).ready(function() { ...

Create an image on a node's backdrop using a library of graph theory/networking techniques

I have a set of data that I need to visually represent as a graph on a web browser. While creating the graph itself is not an issue, I am looking to dynamically draw unique icons for each node. These icons are specific to the characteristics of each node ...

Hide all elements in jQuery that do not have a class assigned

I've implemented a straightforward jQuery script that toggles the "active" class on an li element when it is clicked: $('li').click(function() { $(this).toggleClass('active'); }); My goal is to hide all other li elements in t ...

JavaScript: abbreviated way to selectively append an element to an array

Currently, I am in the process of creating a Mocha test for a server at my workplace. When dealing with customer information, I receive two potential phone numbers, with at least one being defined. var homePhone = result.homePhone; var altPhone = ...

Using Selenium IDE to perform comprehensive tests on all website links

Currently, I am in the process of utilizing Selenium IDE for testing a web application. The page in question contains multiple links that trigger modal windows. My goal is to test every single link on the page in order to confirm that they all result in mo ...

Accumulation of style from various directives in AngularJS on a single element

Currently, I am working on developing a component framework and find myself in need of a method to apply styles from multiple directives to an element in a way that they can accumulate. The priority of the styles should be determined by the directive creat ...

Fade in/out overlay effect when clicking on a content block

I've hit a roadblock while trying to implement overlay fading in and out to cover a block created by some JavaScript code. Here is a link to the project. When you click on any of the continents, a series of blocks with country flags will appear. You& ...

Problem encountered while revalidating Next.js and Sanity documents through a webhook

I'm currently developing a Next.js 13 project that utilizes Sanity as its CMS and is deployed on Vercel. To ensure that components and pages are revalidated whenever a new testimonial is added, updated, or removed in Sanity, I have configured a webhoo ...