Exploring the functionality of async functions that utilize the await feature within the Karma and Jasmine JavaScript

Attempting to test an async function using Karma and Jasmine in an AngularJS v1.5.0 project. This async function, labeled as (a), contains 2 await statements:

async function a(){
    let var1 = await b()
    console.log(var1)
    let var2 = await c()
}

function b(){
    return $http.get(url1).then(
        function(response){
            ...
        }
    )
}

function c(){
    return $http.get(url2).then(
        function(response){
            ...
        }
    )
}

The testing scenario is as follows:

it('testA', inject(async function($httpBackend) {
    $httpBackend.when('GET','url1').respond(200, [myresult])
    $httpBackend.when('GET','url2').respond(200, [myresult])
    MyController().a()
    $httpBackend.flush();
}));

The issue arises when calling $httpBackend.flush();. It seems to only 'flush' the first await statement, causing the execution of function 'a' to halt before reaching console.log(var1). Assistance in resolving this problem would be greatly appreciated.

It is important to note that modifications to the actual code are not allowed, the objective is solely to create a reliable test for it.

Attempts to use await a() within the test have proven unsuccessful, as it does not even resolve the initial await statement.

Answer №1

Consider giving this code snippet a shot, sourced from this helpful response

it('testA', inject(async function($httpBackend) {
    $httpBackend.when('GET','url1').respond(200, [myresult])
    $httpBackend.when('GET','url2').respond(200, [myresult])
    MyController().a()
    try {
        httpBackend.flush();
    } catch (e) { } 
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
}));

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

Trigger the errorPlacement function of the jQuery Validation Plugin on events like onfocusout, keyup, and click

Currently, I am utilizing the jquery validation plugin and aiming to utilize the errorPlacement function in order to include error messages to the fields title attribute and display only a ✘ next to the field. Everything works as intended when the form ...

React code to automatically scroll to the top of the page when the user clicks the

Whenever the URL changes or the page is reloaded in my project, I need it to scroll back to the top. While most scenarios work fine, I'm encountering an issue with the browser's back button. Despite a change in the pathname, the page fails to scr ...

What is the procedure for matching paths containing /lang using the express middleware?

I need to target paths that contain /lang? in the URL, but I am unsure how to specifically target paths that begin with /lang? I have two routes: app.get('/lang?..... app.get('/bottle/lang?....... I want to target these routes using app.use(&a ...

Inform the user that an error has occurred when attempting to perform an invalid

While using redux promise middleware for my front end, I am wondering about the correct status code to throw from my backend in case of an error. I know that I can use res.status(500).json(something), but is 500 the appropriate code for all types of erro ...

The Rails base file contains a function, let's call it function A, which calls another function, function C. However, function C is defined in two separate JavaScript files

My project includes an application_base.js file with a function: function drawLocations(canvas, blag, blah) { //do some stuff selectLocations(a_something, b_something); //do some stuff } For Page 1: page_1.js function selectLocations(a_somet ...

Safari: Fixed-positioned DIVs staying put after DOM updates

Hey there! I've been experimenting with animating absolutely positioned DIVs on my webpage using some JavaScript to update the top and left CSS properties. It's been working smoothly in Chrome, Firefox, and even Internet Explorer 8. However, I e ...

Setting a value to a variable in AngularJS is crucial for proper data

How come I'm encountering difficulty in assigning a value to $rootScope when using the code below? fetchIp().then(function(response){ $rootScope.nodeIp = (response.length == 0 ? "localhost" : response[0]); }); var root = 'http://& ...

Unit testing in Angular - creating mock services with observables

I'm currently facing an issue with my unit tests for a component that subscribes to an Observable from the service DataService in the ngOnInit() lifecycle hook. Despite my efforts, I keep encountering the error message TypeError: Cannot read propertie ...

Issues with integrating WordPress into a subapp using AngularJS and web API in IIS?

I have developed an application in IIS and successfully configured my Wordpress site, mapping the URL as . Within that application, I created two sub-apps to publish my AngularJS app and web API. The URL of the app then became , but unfortunately, the log ...

What is the best way to switch from http to https in a React application?

When performing audits in Chrome, I encountered a net::ERR_EMPTY_RESPONSE error because Lighthouse was not able to consistently load the requested page. Google developers have recommended configuring my server (possibly node.js) to redirect from http to ht ...

I'm puzzled as to why a div tag suddenly becomes invisible when I attempt to link it with a v-for directive in my code

I am facing an issue with the div tag assigned to the log class. My objective is to populate the text using data retrieved from the API response. However, when I attempt to include the v-for directive, the entire div mysteriously disappears from the brow ...

What is stopping me from injecting an Angular controller?

After some consideration, I made the decision to alter the way in which I inject my controller. I successfully utilized the "$inject Annotation" method, following the instructions provided here. NetworkInterfaceDetailedViewController.$inject['$scope& ...

Stop Caching with Jquery Infinite Scroll (IAS)

I am using jQuery + IAS to implement infinite scroll functionality on my website. However, I have encountered an issue where the cache is being disabled when making requests for new content. Specifically, the URL that is accessed to retrieve the next page ...

Error message: ngRepeat does not allow duplicate elements in an array

Upon review, I discovered this particular piece of code: <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <script> var app = angular.module("myS ...

What are the steps to creating a unique event within an AngularJs service?

In the midst of my AngularJs project, I find myself faced with a dilemma. I have a service designed to manage button events, but I want another service to handle these events indirectly without directly interacting with the buttons themselves. So, my goal ...

Show real-time server responses using jQuery while waiting for the AJAX request to complete

I have a challenge in creating a function that displays the server response while waiting for Ajax to complete. Here's the scenario: I have selected 10 checkboxes. When I click the submit button, Ajax is triggered. On the server side, there is a loo ...

Tips for optimizing the use of angular-filter

I am currently attempting to group items in my application using the group by feature. In order to do this, I have included and referenced the angular-filter.js file. However, when trying to utilize the filter, I am encountering the following error: Unknow ...

Is it possible to retrieve the ng-model name from an element?

Is there a way to determine the ng-model of the active element? Suppose I have document.activeElement, how can I identify its corresponding ng-model? <input ng-model="myModel"> For example, if the above input field is active, how can I determine th ...

What is the best way to search for a CSS selector that includes an attribute beginning with the symbol '@'?

Whenever I want to target an element with a click event, I usually use the following jQuery selector: $('div[@click="login()"]') <div @click="login()"> Login </div> However, when I tried this approach, it resulted ...

What steps can I take to resolve the TypeError in next js where I am unable to set properties of undefined for 'className'?

I've been working on a Next.js project and I've copied some code from CodePen that is used for designing product layouts on an e-commerce website. However, I'm encountering a problem with the following error message: TypeError: Cannot set pr ...