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

What is the best way to implement a tooltip that appears only when the mouse hovers over a button within an item in vis.js timeline?

While working with vis.js timeline, I successfully created a timeline. However, I encountered an issue where the tooltip was appearing on the entire item instead of just when hovering over the button. I tried using the title attribute for the tooltip, bu ...

Troubleshooting issues with AngularJS $watch not triggering properly

Even though Deep watch has been activated in the factory, it is not triggering. What steps can be taken to resolve this issue and ensure that an event is triggered when the 'name' value changes? Javascript Code: var app = angular.module('a ...

Go back to the pop-up window if an error occurs

I've implemented a modal window in front of my index page. When the model is valid, I redirect to the index view. However, when the model is not valid, I want it to stay on the modal. How can I achieve this? [HttpPost] [ValidateAntiForgeryToken] publ ...

Steps to retrieve data (token) from developer tools and incorporate it into a fetch Post request

Is there a simple way to extract data using dev tools and insert it into a fetch request? I am trying to make a POST request through the console, but I am struggling to correctly copy a token. I attempted to use querySelector but instead of finding the t ...

The modal popup will appear in the center of the screen when the scrollbar is positioned at the top

I have a modal popup that is not consistently displayed in the center of the screen, regardless of the scrollbar position. I always want it to render at the center so the user doesn't need to scroll to see it. Below is the code I am currently using: ...

AngularJS Blob method causing downloaded documents to become corrupted

I was able to download files successfully in my application until I upgraded Angular to the latest version. However, after the upgrade, the downloaded files are getting corrupted. The upload functionality is still working fine and the files on the server a ...

Having trouble sorting data-text values that include colspan cells

Latest Update: Encountered an issue with incorrect sorting and frozen sortings when dealing with a cell containing the colspan attribute. Refer to https://jsfiddle.net/2zhjsn31/12/ where the problem arises for the date 2018-06-24 On https://jsfiddle.n ...

JavaScript Array Problem

Could you please review the code below and help me understand why I am encountering issues when trying to run the program? $(document).ready(function() { var comp = new Array("AAPL", "MSFT", "XRTX&"); var t = setInterval(function(){ ...

Exploring the wonders of Node.js, Redis, and Express.js while navigating through the enchanting world of Asynchronous

Hello there, I must confess that this is a whole new realm for me... Here is what we've got: app.get('/user/:user_id/followings', function(req, res) { var response = {} , userId = req.params.user_id , ids = req.param(' ...

Angular directives with templateUrl pointing to 'from my own server'

Hello there, I am a newcomer to Angular and I have a small inquiry. Currently, I am successfully rendering my partials using the $routeProvider from the server, but I am uncertain if the same can be achieved from a directive? For example: myapp.directiv ...

What is the best way to invoke a controller method using jQuery within a cshtml file?

I am working on a project where I need to add user information to the database by calling a function in my controller class. The user's information is entered through a form created in a .cshtml file that interacts with an external JavaScript file. Is ...

Mastering the art of utilizing drag and drop features for both columns and rows in a React Table within ReactJS

I have managed to create a React Table with columns and rows, but now I'm looking to incorporate drag and drop functionality for both. Does anyone know how I can achieve this? Feel free to check out my CodeSandbox Sample here - https://codesandbox.io ...

What causes a decrease in speed when a function is called without specifying its owner?

Let's consider the following scenario: var abs = Math.abs; Wouldn't abs(-10) be quicker than Math.abs(-10)? Since abs is called directly. This caught my attention: Math.abs vs custom abs function Update: The same test conducted in Internet ...

Can a single-page application be created using Express without utilizing React, Angular, or similar frameworks?

Our codebase is currently exclusively built on express, and we are looking to expand it while transitioning into a single page application. At this point in time, I am hesitant to rework the code using frameworks such as Angular or React to achieve this go ...

What criteria should I consider when selecting a make for the createTheme components?

After reviewing the documentation for the createTheme component, I noticed examples with MuiButtonBase, MuiButton, and MuiSlider. However, when it comes to adding a button, it's simply called Button, not MuiButton. So, does this mean I just need to p ...

"Assigning a value to an Angular directive within an ng-repeat loop

I've been trying to assign values from ng-repeat to a customized directive, but unfortunately, the value is being set outside of the repeater instead of inside it. HTML: var app = angular.module('testApp', []); app.controller('test ...

Leveraging data schemas to manage the feedback from APIs

I am curious about the benefits of modeling the API response on the client side. Specifically: First scenario: const [formData, setFormData] = useState(null); ... useEffect(() => { const callback = async () => { try { const fetchDa ...

After applying the cellClass in ng-grid, the row border mysteriously disappears

After applying cellClass to color an entire column, the row border disappears. Here is a link to the Plunker demonstration: http://plnkr.co/edit/4IeQQBTIe8sgHVEBUTAp?p=preview. Does anyone have a solution for this issue? ...

When attempting to submit a record at http://localhost:5173/, a 404 (Not Found) error was

Currently, I am attempting to retrieve username data and timeTaken from a form. My goal is to send this data to my server, create the User object, and store it in MongoDB Atlas. Unfortunately, I am encountering a 404 error that I am struggling to resolve. ...

The closing brackets in PHP substr() function are causing style issues

Here's the scenario: I entered a large amount of content in a text editor (WordPress). Now, I want to display this content on my homepage using PHP queries. In order to limit the content size to 100-200 characters, I used the substr() function i ...