Jest is a powerful tool for testing AngularJS applications

I am currently experimenting with simulating HTTP requests for AngularJS in Jest.

Presently, I have a service structured like this:

public UserService(user) { 
    let url = this.env.getUserEndpoint("/users"); 
    let deferred = this.$q.defer<any>(); 

    this.$http.post<{ user: IUser }>(url,user).then( (result) => {
        deferred.resolve(result.data.user); 
    }, (error) => { 
        deferred.reject(this.httpErrorHandlingService.handleHttpError(error, "creating new user")); 
    }); 

    return deferred.promise;
}

In terms of testing:

beforeEach(angular.mock.module("test"));

var userService;

beforeEach(angular.mock.inject(function (UserService) {
    userService = UserService;
}));

it('should be able to initiate the creation of a new user', function () {
    const newUser = {
        name: "testUser",
        password: "12345"
    };

    return userService.createNewUser(newUser).then(user => expect(user.name).toEqual("testUser")
});

The issue I'm encountering is

Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout

I would appreciate some guidance on what mistakes I might be making and any tips on how to effectively mock AngularJS HTTP requests.

Answer №1

No need to reinvent the wheel - $http.post() already provides a promise for you. Simply tap into the response data within your success and error function callbacks using the then method. This streamlined approach can help tidy up your service code:

class UserService { 

    createNewUser(user) {
        let url = this.env.getUserEndpoint("/users"); 

        return this.$http.post<{ user: IUser }>(url, user).then((result) => {
            return result.data.user; 
        }, (error) => { 
            this.httpErrorHandlingService.handleHttpError(error, "creating new user"); 
        });
    }
}

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

Obtain the current user's Windows username without relying on the ActiveX object

Is there a way to retrieve a client's Windows username in ASP.NET when hosted on a remote server without using an ActiveX object? I tried the following code: Response.Write("HttpContext.Current.Request.LogonUserIdentity.Name " & HttpContext.Cur ...

Tips for resolving circular dependencies: When Vuex requires JS modules that are dependent on Vuex

I am facing a challenge with my Vuex store, as it imports the notifications.js module that requires access to Vuex.store.state. How can I resolve this issue? Currently, I am passing store.state as a prop to address the circular dependency. Is there a more ...

What is the best approach to identify duplicated objects within an array?

I have an array with a specific structure and I am looking to add non-duplicate objects to it. [ { applicationNumber: "2", id: "8cca5572-7dba-49de-971b-c81f77f221de", country: 23, totalPrice: 36 }, { applicationNumber: "3", id: "8cc ...

Developing a vertical accordion menu with AngularJS

Looking to create a sleek vertical accordion menu using a combination of angularjs, jquery, and css. If anyone has expertise in this area, I would greatly appreciate some guidance on how to integrate these technologies seamlessly. Your assistance is much ...

Guide to displaying dashboard components within the same page

I have a Dashboard Component with a side nav that contains menu items such as Dashboard, Manage Companies, ContactUs, and Manage Users. When clicking on Dashboard, I want to render the dashboard component on the same page. Similarly, when clicking on Manag ...

The results generated by the Google Maps API are consistently consistent

const request = require('request'); var geocodeAddress = (location) => { var encodedLocation = encodeURIComponent(location); request({ url: `http://www.mapquestapi.com/geocoding/v1/address?key=APIKey&location=${encodedLocation}` ...

Transforming a callback function into a Promise: A step-by-step guide

I'm currently utilizing Bluebird promises and attempting to make the following function work with Promisify: var jwt = require('jsonwebtoken'); function _test_encode() { var cert = fs.readFileSync('public.pub'); return j ...

ReactJS: An error occurred - TypeError: this.state.items.map is not a function

As a beginner in ReactJS, I am working on my first project which is a To-Do List with drag and drop feature, add, delete, and edit functionalities. I encountered an error while trying to map an array upon submitting a text to add an item to the items array ...

Tips for sending a successful POST request with the MEAN stack

Currently, I am utilizing yeoman to set up a new project. My ultimate goal is to master the process of scaffolding CRUD operations. However, I have encountered an issue with a post request. For this reason, I opted for the angular-fullstack generator as I ...

Incorporating Subtitles into Videos using NodeJS and the FFMpeg Fluent API

I'm having trouble adding subtitles (srt) to a video stream using Node JS and FFMpeg... Here's what I've tried: var command = ffmpeg(file.createReadStream()) .input("C:\\code.srt").videoCodec('copy') .videoCodec(& ...

Converting datetime to time format

I have a datetime column in the format of YYYY-MM-DD HH:mm:ss.SSS. Is there a way to display only the time in the format of HH:mm:ss.SSS without showing the complete datetime? I have attempted the following code, but it does not seem to affect the format: ...

Utilizing Vue's computed function to filter values from a JSON dataset

How do I efficiently filter an array of JSON data? Here is the code snippet: <div v-if="vacciCounter"> <b-card no-body class="mb-2" v-for="(stateObject, state) in filteredList" v-bind:key="state"& ...

On iOS devices, background images may not appear in the Home Screen after being added

My CSS code looks like this: #thumbnail { background-image: url(bla.jpg), background-size: cover, background-repeat: no-repeat; background-position: 50% 50%; } While it displays fine on iOS Safari and other platforms, the image does not s ...

Customize form input using Javascript prior to inserting into database

On my Rails form, I have a basic setup like the following: <%= form_for @song do |f| %> <p> <%= f.label :url %><br> <%= f.text_field :url %> </p> <p> <%= f.submit %> </p> <% en ...

Filtering an RXJS BehaviorSubject: A step-by-step guide

Looking to apply filtering on data using a BehaviorSubject but encountering some issues: public accounts: BehaviorSubject<any> = new BehaviorSubject(this.list); this.accounts.pipe(filter((poiData: any) => { console.log(poiData) } ...

Countdown with precision! This timer will begin at the one-hour mark

Having an issue with my JavaScript stopwatch. When I hit the start button, the stopwatch immediately shows one hour (01:00:00) before counting normally. Any solutions to prevent this instant start at one hour would be highly appreciated. Thank you in adv ...

Enhance the functionality of a form by dynamically adding or deleting input rows using

The feature for adding and deleting input rows dynamically seems to be experiencing some issues. While the rows are successfully created using the add function, they are not being deleted properly. It appears that the delete function call is not function ...

Leveraging the capabilities of Express functions on the client side through the require method in Node.js

Trying to access the configuration variables set in the file named test.js which contains -- var aws = require('aws-sdk'); exports.connect = function(){ return aws; } Now, I am attempting to access it upon an OnClick event taking place ...

Drag and drop functionality in Angular 4

I'm currently facing an issue with Angular drag and drop. I have created a component along with a directive for this purpose. Initially, I tried one solution which involved the following code: @HostListener('drop', ['$event']) pub ...

"Error 404: The file you are looking for cannot be found on [custom company domain]. Please check

My attempts to retrieve a Google Drive file using its file ID with a service account in NodeJS have been unsuccessful. The requests are failing with an error indicating a lack of access: code: 404, errors: [ { message: 'File not found: X ...