Issue with AngularJS promise not returning any value in JavaScript

I have been attempting to perform a simple HTTP post in a unit test using Jasmine, but unfortunately, it is not functioning as expected. The application operates smoothly on the web, and I have individually tested various functions, all of which work seamlessly. However, this specific function refuses to cooperate.

describe('Service: Auth',function(){

    beforeEach(function () {
        module('ui.router');
        module('main');
        module('users');
    });

    var AuthFactory, httpBackend;

    beforeEach(inject(function($httpBackend, _AuthFactory_) {
        httpBackend = $httpBackend;
        AuthFactory = _AuthFactory_;
    }));

    it('should return POST', function() {
        AuthFactory.signIn({inputUser: {username: "admin"}, passInput: {password: "adminpass"}}).then(
            function(result) {
                console.log('======== SUCCESS ========');
                console.log(result);
            },
            function(err) {
                console.log('======== ERROR ========');
                console.log(err);
            },
            function(progress) {
                console.log('======== PROGRESS ========');
                console.log(progress);
            }
        );
        console.log('HTTP call finished.');
        expect(1).toBe(1);
    });

});

and here lies the factory:

angular.module('users').factory('AuthFactory', ['$http', function($http) {

    var AuthFactory = {};

    AuthFactory.signIn = function(data) {
        return $http.post('http://127.0.0.1:3000/api/AuthFactoryServ/signIn', data);
    };

    AuthFactory.signOut = function(data) {
        return $http.post('http://127.0.0.1:3000/api/AuthFactoryServ/signOut', data);
    };

    return AuthFactory;

}]);

This is what I am encountering:

PhantomJS 1.9.8 (Windows 7 0.0.0): Executed 0 of 1 SUCCESS (0 s
LOG: Object{$$state: Object{status: 0}, success: function (fn)
{ ... }, error: function (fn) { ... }}
PhantomJS 1.9.8 (Windows 7 0.0.0): Executed 0 of 1 SUCCESS (0 s
LOG: 'HTTP call finished.'
PhantomJS 1.9.8 (Windows 7 0.0.0): Executed 0 of 1 SUCCESS (0 s
PhantomJS 1.9.8 (Windows 7 0.0.0): Executed 1 of 1 SUCCESS (0 s
PhantomJS 1.9.8 (Windows 7 0.0.0): Executed 1 of 1 SUCCESS (0 secs / 0.022 secs)

I have verified that the HTTP calls function properly via Postman and return the expected data. So, where might I be erring?

Many thanks.

Answer №1

When using the AuthFactory.signIn function, keep in mind that it is asynchronous and returns a promise. Your test function may complete before the promise resolves.

To ensure Jasmine waits for the asynchronous test to finish, you should notify it accordingly:

it('expects a POST response', function(done) {
  var result = AuthFactory.signIn({inputUser: {username: "admin"}, passInput: {password: "adminpass"}}).then(
      function(result) {
          console.log('======== SUCCESS ========');
          console.log(result);
      },
      function(err) {
          console.log('======== ERROR ========');
          console.log(err);
      },
      function(progress) {
          console.log('======== PROGRESS ========');
          console.log(progress);
      }
  );
  result.then(function(){
    console.log('HTTP call completed.');
    expect(1).toBe(1);
  }).finally(done); // attaching Jasmine callback to the promise chain
});

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 AJAX response consistently returns a 405 status code

I am experiencing an issue with an AJAX post request. $.ajax({ type: "POST", contentType: "application/json", url: "/rating/save", data: JSON.stringify(rating), dataType: "json", mimeType: "application/json" ...

Running a server-side function on the client-side in Node.js

I am currently working with the following code snippet on the server: var game = io.listen(app); game.sockets.on('connection', function(socket){ storePlayers(socket.id); //Only the player who connects receives this message socket.em ...

Proper utilization of ngIf in conjunction with mat-cell

I am attempting to show a specific value only if the item possesses a certain property, but I keep seeing [object Object] instead. Here is my current method: <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDe ...

Angular's innerHTML dilemma

Within my Angular service, I have implemented three methods as shown below: public loadLiveChat() { let url: string; url = this.appConfig.config.liveAgent.liveAgentScriptUrl; this.dynamicallyLoadScript(url); ...

What is the best way to incorporate a button for toggling CSS animations?

I need help adding a button to toggle the animation on this JSFiddle. I tried adding the code below but can't seem to start and stop the animation. body .a [class^="b"] { width: 200px; height: 142.8571428571px; margin: 0 auto; ...

After deploying on Vercel, Next.js' getServerSideProps function is returning undefined

I am trying to create a Netflix-inspired website using next.js. I am able to fetch movie data from TMDB using getServerSideProps(). While everything works as expected in development mode, once deployed on Vercel (re-deployed multiple times), the props I re ...

Experimenting with two iterations of the json-schema to ensure compatibility across different versions

I manage a repository that stores versioned json-schemas, meaning I may have multiple revisions for each type of schema (v1, v2, v3, etc). My goal is to test these schemas for backwards compatibility, ensuring that any data valid for a v1 schema will also ...

Configuring IIS Rewrite can be easily achieved by following these simple

My project utilizes PHP and Angular, hosted on IIS. I have enabled the html5Mode in Angular, allowing me to use routes like localhost/home instead of locahost/#/home. The issue arises when I copy and paste the URL (for example: http://localhost/home) into ...

Frequently, cypress encounters difficulty accessing the /auth page and struggles to locate the necessary id or class

When trying to navigate to the /auth path and log in with Cypress, I am using the following code: Cypress.Commands.add('login', (email, password) => { cy.get('.auth').find('.login').should(($login) => { expect($log ...

I keep encountering the issue of receiving a "name undefined" error message while attempting to make a post request with Express and Body Parser

I've been working on building a MEAN app and encountered an issue while testing POSTing with POSTMAN. Every time I attempt to POST, I receive the error message "TypeError: Cannot read property 'name' of undefined". Strangely enough, if I inp ...

Undefined Children Component

I am currently working on creating Auth routes and I am facing an issue where the children are undefined, resulting in a blank page. In my App.js file, I have implemented a PrivateRoute component as shown below. Interestingly, when I replace PrivateRoute w ...

What causes a service called from external of angular to not act as a singleton?

Currently, I am in the process of working on a project that requires me to access a service from outside the Angular service. Unfortunately, it seems that the service retrieved from outside of Angular is not the same instance as the one inside the applicat ...

Unable to stop the default action in IE for certain code

I am facing an issue on my website where the JavaScript I have implemented to prevent page reload is not working in Internet Explorer. The code functions properly in all other browsers, except IE. Here is the JavaScript code snippet that should prevent pa ...

Is it necessary for the key in JSON syntax to be enclosed in quotes?

I am facing an issue with converting a specific string to JSON format. Here is the string: '{clientId: "1239268108.1505087088", userId: "0.4744496956388684", "url": "http://boomfix.es/", "pageUrl": "1", "timer": "15", "clickCount": "4", "mouseMax": " ...

Tips for calculating the difference between timestamps and incorporating it into the response using Mongoose

In my attendance model, there is a reference to the class model. The response I receive contains two createdAt dates. const attendanceInfo = await Attendance.find({ student: studentId, }) .populate('class', 'createdAt'); ...

Exploring Object Array values with Javascript

I am working with an Object array and I need to implement a contains filter for every property. This means that the search should look for a specific keyword in any of the properties and return the object if it finds a match. Can you please provide guidanc ...

Navigating poorly structured HTML tables using jQuery code loops

I am currently working on a project that involves an HTML table generated by my client, and it seems like we are both in agreement not to change how the code is generated at this time. <TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0> <TR HEIG ...

Learn how to obtain a response for a specific query using the `useQueries` function

Can we identify the response obtained from using useQueries? For instance, const ids = ['dg1', 'pt3', 'bn5']; const data = useQueries( ids.map(id => ( { queryKey: ['friends', id], queryFn: () =&g ...

Python Scrapy: Extracting live data from dynamic websites

I am attempting to extract data from . The tasks I want to accomplish are as follows: - Choose "Dentist" from the dropdown menu at the top of the page - Click on the search button - Observe that the information at the bottom of the page changes dynamica ...

"What is the best approach to adjusting the width of one div based on the width of another div using CSS Grid

As a beginner in programming, I'm trying to work with CSS Grid but facing some challenges. My goal is to create a component with two columns: the left column should have a width of minmax(570px, 720px), and the right column should be minmax(380px, 10 ...