Jasmine was disappointed when the promise from a simulated factory was rejected

Snippet of my controller's initialization process:

    var initialize = function () {
        httpUsers.fetchUsers().then(function (data) {
            $timeout(function() {
                // Perform some actions...
            });
        }).catch(function (error) {
            vm.error = "Oops!";
            toastr.error(error);
        });
    }

Mocked service for testing purposes:

beforeEach(function() {
    module('httpService', function($provide) {
        $provide.factory('httpUsers', function () {

            var service = {
                fetchUsers: fetchUsers
            }

            function fetchUsers() {
                deferred = $q.defer(); 
                deferred.resolve([
                    { id: 1, firstName: "John", lastName: "Doe" },
                    { id: 2, firstName: "Jane", lastName: "Doe" },
                    { id: 3, firstName: "Jack", lastName: "Doe" }
                ]);
                return deferred.promise;
            };

            return service;
        });
    });
});

Everything is working smoothly with the resolved promise.

I am now looking to test the catch scenario in my controller's initialization method.

This is what I have tried:

describe('initialize', function() {
    it('should handle error properly', function () {
        deferred.reject('sample error');
        expect(controller.error).toBe("Uh oh!");  
    });
});

However, the output received is:

Expected undefined to be 'Uh oh!'.

Neither 'sample error', nor 'Oops!', nor 'Uh oh!' are displayed. How can I forcefully trigger a rejection on the promise during testing?

Thank you!

Additional Information
Here is how my controller is injected:

beforeEach(inject(function(_$controller_, _$rootScope_, _$q_, _$timeout_, _global_) {

    $rootScope = _$rootScope_;
    $scope = _$rootScope_.$new();
    $q = _$q_;
    $timeout = _$timeout_;
    global = _global_;

    controller = _$controller_('usersController', {
        $rootScope: $rootScope,
        $scope: $scope,
        $q: $q
    });

    $timeout.flush();
}));

Answer №1

Here is an example of what you can do with your mock service:

beforeEach(function() {
    module('httpService', function($provide) {
        $provide.factory('httpUsers', function () {

            var service = {
                getUsers: getUsers
            }

            function getUsers() {
                deferred = $q.defer(); // deferred is a global variable
                return deferred.promise;
            };

            return service;
        });
    });
});

Test for rejection:

describe('init', function() {
    it('should throw error', function () {
        deferred.reject('testing');
        $scope.$apply();
        expect(controller.error).toBe("Error!"); 
    });
});

Test for resolve:

describe('init', function() {
    it('should throw error', function () {
        deferred.resolve([
                    { id: 1, firstName: "John", lastName: "Doe" },
                    { id: 2, firstName: "Jane", lastName: "Doe" },
                    { id: 3, firstName: "Jack", lastName: "Doe" }
                ]);
        $scope.$apply();
        $timeout.flush();
        expect(controller.error).toBe("Error!"); 
    });
});

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

Disabling JavaScript for a particular page using Selenium:

My current challenge involves navigating to a webpage, locating a link to another page within it, and proceeding to that link without using javascript. One approach I've considered involves the following method: options = Options() options.add_exper ...

Trouble getting the onclick event to function properly with PHP, ajax, and jQuery

I am looking to incorporate an onclick event using PHP to achieve a specific goal. My aim is to utilize ajax to prevent page refreshing and generate buttons upon click events. I am uncertain about merging the div buttons with the ajax outcome. The PHP fi ...

Tips for passing a state value to a different state when initializing in react js

I need some help with passing a state value called imagesArray to another state named tabData. It seems like the value is coming up as undefined. Below is the code snippet, can you please point out what I might be doing wrong? constructor(props) { s ...

What is the best way to create a function library that works seamlessly across all of my Vue.js components?

I am currently in the process of developing a financial application using Vue.js and Vuetify. As part of my project, I have created several component files such as Dashboard.vue Cashflow.vue NetWorth.vue stores.js <- Vue Vuex Throughout my development ...

Having trouble with Vue component not updating Vuex state before it loads?

At times, the token is committed to Vuex store while other times it is not. userLogin() { axios.post('api/login', this.logindata,) .then(response => { let token = JSON.parse(localStorage.getItem('token')); t ...

The getElementBy method is failing to pass the value in the document

Here is the javascript code snippet I am using: document.getElementById('district').value = dist.long_name "this line is passing the value" document.getElementById('city').value = route.long_name "this doesn&apos ...

`Receiving JSON data using AngularJS and Ionic: Fixing Errors`

Unable to display small JSON data from the server on an HTML file. Spent hours trying to troubleshoot but no luck. Any suggestions or ideas? Thank you for your help. JS File: (function() { var app = angular.module('myreddit', ['ionic&apos ...

Customize Link Appearance Depending on Current Section

Looking for a way to dynamically change the color of navigation links based on which section of the page a user is currently viewing? Here's an example setup: <div id="topNav"> <ul> <li><a href="#contact">Contac ...

The token endpoint in Nuxtjs auth module's configuration for auth strategies is not being triggered

Our system has two important endpoints, namely /auth and /token. The endpoint /auth is responsible for providing the authorization code required to call /token in order to obtain an access token. The utilization of NuxtJS has made the auth module a prefer ...

keeping variables hidden from the user until a certain action is taken

In my project, I am working with three main code classes: 1) node.js (utilizing express framework) 2) index.html (serving as the home page when users visit the site) 3) sck.js which performs a specific function (details to follow on the first and second fi ...

Is it possible to dynamically group by one column in a dataset without requiring a trigger function?

I've been working on a script that retrieves values from another page and organizes them into a table alphabetically by Name, City, and District. The current script is functioning well, but I now want to enhance it by grouping the values by city as we ...

Troubleshooting: The issue of Vue JS not successfully navigating between web

After countless attempts, I am still struggling to get my Firebase login function to appropriately switch the component upon signing in. I urgently need assistance with configuring my router to seamlessly transition to the next page once the sign-in proces ...

Encountering a "Module not found" error while trying to run npm start in a Create React App

I'm attempting to initiate a React project using create-react-app. Encountered an error when running npm start: Failed to compile. multi ./node_modules/react-scripts/config/polyfills.js ./node_modules/react-dev-utils/webpackHotDevClient.js ./src/i ...

Customize AngularJS: Make the default child view for UI-View stand out

I came across a guide on how to set up nested states in AngularJS using UI Router, and followed it to create a page with two child views. Now that everything is set up, clicking on specific links displays the subviews as expected. Below is my app.js file ...

Turn on and off scrolling of DIV content when hovering over it

How can I create a div that automatically scrolls to the bottom on hover? I tried implementing the code below, but it doesn't work as expected. It jumps to the bottom of the div's height on first hover and transitions smoothly on second hover. . ...

Retrieve JSON data generated within a JavaScript-powered webpage

My issue involves two HTML pages: 1) The first HTML Page (page1.html): <html lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script> <script type="text/ ...

Ways to determine if the v-menu is currently visible or hidden

I am currently working on a button with a logo displayed. The hover functionality is working fine, but I want the icon to change to a hamburger when the menu is opened and stay that way. Is there an option in v-menu that checks if the menu is open or shoul ...

What is the process for accessing an uploaded file in a server-side Classic ASP page?

I'm attempting to use Ajax to upload a file to a server-side script in classic ASP. Here is the relevant HTML and JavaScript code: <input type="file" id="fileInput" /> and function saveToServer(file) { const fd = new FormData(); fd.a ...

Discovering the clicked element using JavaScript: A complete guide

Let me start by saying that I have come across similar posts about tracking event listeners, but in my specific case, I am struggling to figure it out. While I am familiar with the event.target property, I just can't seem to make it work. Here is a s ...

Be mindful of potential missing dependencies when utilizing event listeners and states within useEffect

Whenever I utilize the addEventListener() method alongside trying to access some state within the useEffect, I consistently face the same issue. Adding the state as a dependency is not an option, as that would result in multiple event listeners being creat ...