Unfulfilled promises are left hanging

I've encountered a problem while writing a unit test for my Angular application using Jasmine with a mock service. The promise I am trying to run is not functioning as expected.

Below is the service code:

CreateItemController = $controller('CreateItemController', {
    ItemService: {

        createItem: function(data) {
            console.log('Service running');
            var defer = $q.defer();
            defer.resolve('1');
            return defer.promise;   
        }

The test script looks like this:

it('should create an item', function() {

    var created = false;
    $scope.createItem().then(function(response) {
        // This section is not executing
        console.log("We got through");
        created = true;
    });

    expect(created).toBe(true);

})

And here's the actual function implementation:

$scope.createItem = function() {
    var postData = {
        name: 'Jeans'
    };

    return ItemService.createItem(postData).then(function(response) {
       // This part is also not running
       console.log('Promise received');
    });
}

Can anyone help me figure out what mistake I'm making?

Answer №1

To enhance your test, consider mocking the $q service to ensure that the promise resolution is no longer asynchronous.

Testing the $q service itself is unnecessary; focus on testing your custom logic instead.

  describe('controller: CreateItemController', function () {
    var subject, $scope;
    beforeEach(module('myModule'));
    beforeEach(inject(function ($rootScope, $controller, $q) {
      $scope = $rootScope.$new();

      subject = $controller('CreateItemController', {
        $scope: $scope,
        ItemService: {
          createItem: function () {
            var defer = $q.defer();
            spyOn(defer.promise, 'then').andCallFake(function (callback) {
              callback();
              return this;
            });
            return defer.promise;
          }
        }
      });
    }));

    it('should create an item', function () {
      var created = false;
      var subject = $scope.createItem().then(function () {
        created = true;
      });

      //deferred.resolve('1'); // unnecessary as callbacks are triggered immediately

      expect(created).toEqual(true);
    });
  });

If maintaining the delay is necessary, you can invoke $scope.$apply() after resolving the deferred object:

  describe('controlle: stack overflow', function () {
    var subject, $scope, deferred;
    beforeEach(module('myModule'));
    beforeEach(inject(function ($rootScope, $controller, $q) {
      $scope = $rootScope.$new();

      subject = $controller('CreateItemController', {
        $scope: $scope,
        ItemService: {
        createItem: function () {
            deferred = $q.defer();
            return deferred.promise;
          }
        }
      });
    }));

    it('should create an item', function () {
      var expected = {
        one: false,
        two: false,
      };
      var subject = $scope.createItem();
      subject.then(function () {
        expected.one = true;
      }).then(function () {
        expected.two = true;
      });

      deferred.resolve();
      expect(expected.one).toEqual(false);
      expect(expected.two).toEqual(false);

      $scope.$apply();

      expect(expected.one).toEqual(true);
      expect(expected.two).toEqual(true);
    });
  });
});

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

access the passport variable within the ng-view

Hello, I am encountering a slight issue. Here is the structure of my template: <div id="navbar">..... Connected as #{user.username} </div> <div id="main> <div id="ng-view"> Here go my partial templates </div> </div> ...

Challenges encountered when unit testing ngx-translate

0 I am encountering issues with unit testing while using the ngx-translate library. Despite adding a provider for TranslateService, the tests keep asking for more providers, creating an endless loop of dependencies. Specifically, I am trying to unit test ...

Issue with Vuex getter not reflecting correct value after modifying an array

I've been delving into the world of vuex, and I'm currently working on fetching the count or an array when I make additions or removals. Below, you'll find the code snippets I'm working with. home.vue template <template> < ...

invoke a managed bean to execute JavaScript code

I am facing an issue while trying to clear a hidden form value in a JSF page from a managed bean class. I tried calling a method where I used the following code snippet to call JavaScript, but unfortunately it throws a java.lang.NullPointerException. The c ...

How to style focused input using Vue2

I have a form that contains multiple input fields, and I want to dynamically add a class to the label tag of the focused input and remove it when another input is selected. Initially, I tried the following code: onInputSelected: function(e) { var la ...

What is causing my div exchange using .class to fail?

Struggling to convert this code from working with IDs to Classes. The code reveals one Div while hiding another based on the onClick event. Originally, it was straightforward because the div location was absolute. In the classes version, I need to revea ...

Is there a way to prevent SignalR from disconnecting when the settings window is moved?

I am currently developing a webpage that utilizes SignalR events to trigger ajax requests to our servers. These requests return a URL with a custom URI scheme that, when accessed, opens up a specific program on the client's device without leaving the ...

Create compelling visual representations by utilizing Google charts to draw customized charts based on variable

I have been attempting to create a chart using Google Charts by passing some parameters to the function. I am trying to use these parameters to populate the data, but it doesn't seem to be working as expected. Is it possible to include parameters in t ...

Combine es6 imports from the identical module using an Eslint rule or plugin

Looking to consolidate my ES6 imports from a single module into one for my React project. For example: import { Title } from "@mantine/core"; import { Center } from "@mantine/core"; import { Divider } from "@mantine/core"; T ...

Does the react key have scope limited to the local environment or does it have

After reading this intriguing article discussing the use of the index as a react key, I began to ponder. Imagine having two distinct lists: <List1> <el key="1" /> <el key="2" /> </List1> <List2> <other-el key="1" / ...

Express Node fails to launch

I recently decided to try my hand at Express and learn more about it. However, I encountered an issue while trying to start a server. Initially, I attempted to access 127.0.0.1:8080 through Express but nothing seemed to be happening. Although I copied most ...

I'm having trouble getting my HTML POST request form to connect with the Express app.post. Any tips on how to properly pass on numeric variables to a different POST request?

There seems to be a misunderstanding or error on my part regarding POST and GET requests based on what I've read online. On myNumber.ejs, I have a submit form. Upon submission, the view switches to Add.ejs. The goal is for Add.ejs to display both the ...

Revising the input value by updating the properties

After clicking on the Reset link, I encounter an issue where the input value fails to update properly. class DiscountEditor extends Component { render() { <div className="inline field"> <a className="ui reset" onClick={thi ...

Retrieving component attributes using jQuery or alternate event handlers

In my Angular2 component, I am facing an issue with using vis.js (or jQuery) click events. Despite successfully displaying my graph and catching click events, I encounter a problem where I lose access to my component's properties within the context of ...

How can I use JavaScript or JQuery to retrieve the HTML content as a string from a specific URL?

How can I extract the URL of a link from a webpage and add it to my code without an ID for that specific link? Is there a way to search based on the content within the <a> tag? ...

Vue JS encountering Slack API CORS issue while using axios

I am currently developing an application using Capacitor JS & Nuxt JS to interact with the Slack API for setting my Slack status. I have successfully created a Slack App and obtained a xoxp- token, which works perfectly when sending a POST request via Post ...

Ajax fails to transfer the complete data

I am currently facing an issue with my request. Here is the code snippet that I need help with: logInWithFacebook = function() { FB.login(function(response) { if (response.authResponse) { FB.api('/me', {fields: 'name,email,location,p ...

Is it possible to set up a complete operating system within a pod using Kubernetes and run Selenium tests simultaneously?

I'm currently exploring methods to effectively test the Safari web browser. While Kubernetes has proven to be a suitable option for testing browsers like Chrome or Firefox with tools such as Selenoid or Moon, testing in Safari presents its own challen ...

Basic color scheme

I'm attempting to change the background color behind a partially transparent .png div. The CSS class that modifies the div is ".alert". Manually editing the .alert class background color works perfectly, and now I want to automate this on a 1-second c ...

Creating a concise TypeScript declaration file for an established JavaScript library

I'm interested in utilizing the neat-csv library, however, I have encountered an issue with it not having a typescript definition file available. Various blogs suggest creating a basic definition file as a starting point: declare var neatCsv: any; M ...