The async function in Jasmine is causing issues with expectedAsync functionality

Currently conducting the following examination:

it("should receive rejection", async done => {
      class someTest {
        async run(){
          return this.rejectFunc();
        }
        async rejectFunc(){
          return new Promise( (_,reject)=>{
            setTimeout(()=>{
              reject()
            },300)
          })
        }
      }

      const test = new someTest();
      spyOn(test, 'rejectFunc').and.callThrough();
      test.run()      
      await expectAsync(test.rejectFunc).toBeRejected();  
      done();
    });

However, encountering a failure due to timeout:

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

Where is the error in my approach? The goal is to execute the run process and confirm that rejectFunc results in rejection.

Answer №1

I have just come across the expectAsync function for the first time, and it appears to require a promise as an input rather than the name of a function.

To use it correctly, you can try the following:

// Call the function with ()
await expectAsync(test.rejectFunc()).toBeRejected();

Another approach to testing could be:

try {
  await test.rejectFunc();
} catch (error) {
  // Here you can call done(), indicating that the promise was rejected
  // and we can assert that it was indeed rejected
  done();
}

Edit:

const test = new someTest();
spyOn(test, 'rejectFunc').and.callThrough();
try {
  await test.run();
} catch (e) {
  expect(test.rejectFunc).toHaveBeenCalled();
}
    
done();

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

Leverage PHP to dynamically populate a chart.js visualization with information sourced from an SQLite Database

I'm attempting to use chart.js to display data from an SQLite database using PHP, but I've been running into issues. Despite following multiple online tutorials, my graph remains empty or disappears altogether. This is my first time working with ...

Guide on Showcasing Countries on a Global Map with Various Colors Using react-svg-map

I'm currently working on a project that involves highlighting specific countries on a world map. The default color for the countries is light blue, but I need to change it to dark blue for the highlighted ones. Although the library I'm using has ...

Solving the Angular form glitch: error message not displaying

I am facing an issue with my simple form where I am not able to display errors related to the fields. <html lang="en" ng-app="MyApp"> <head></head> <body ng-controller="AppCtrl"> <form name="myForm" id="myForm"& ...

How can I convert a UTC time field from MySQL into JavaScript?

I'm struggling to pinpoint the error in my date/time difference calculations. It seems to be related to timezone variations, but I can't figure out exactly where the problem lies. Below are all the components involved - can you help me identify t ...

Integrate the AWS API Gateway generated SDK into a project managed by NPM

I'm currently in the process of developing a ReactJS application that will interact with backend resources through the API Gateway. I have created a Javascript SDK for my test API, which connects to DynomoDB, and am attempting to integrate it into my ...

Progress bar for uploading files

Similar Question: Upload Progress Bar in PHP Looking for suggestions on a simple and effective method to implement a file upload progress bar. Interested in a solution that involves both javascript and php. Any recommendations? ...

Transferring SQL-generated JSON object from PHP to JavaScript

Seeking assistance with passing a JSON object from PHP to Javascript. The object is populated from an SQL Database using the following PHP code snippet. <?php $conn = mysql_connect("localhost","root",""); if(! $conn ) { die('C ...

Tips for seamlessly incorporating WalletConnect into your decentralized app with the help of web3-react

I have been working on integrating WalletConnect into my project by referring to the documentation provided by web3-react. The configuration settings I am using for the connector are as follows: import { WalletConnectConnector } from '@web3-react/wal ...

What is the best way to arrange an array based on two properties using regular expressions?

Below is an array containing items: var myArray = [ {catNum : 'CAT I #4', trackingNumber : 'ORG Cat-123'}, {catNum : 'CAT I #6', trackingNumber : 'ORG Dog-345'}, {catNum : 'CAT I #2', trackingNumber : ...

Tips for preventing the creation of an element in AngularJS

When working with Angular, I encountered an issue with creating an <iframe> element only upon user interaction. Initially, I simply placed the element on the page and used the ng-if directive to bind its presence to a boolean in my model. However, I ...

What is the best way to position two elements floated to the right in separate rows within a single row?

Having trouble with a web design issue. I am currently working on a website and trying to format an input field with a label so that the label sits on top of the input while floating to the right. However, I'm encountering difficulties as the elements ...

React and React Router are causing the login screen layout to persistently display

The MUI Theme Provider I have includes a Layout with Dashboard and Order screens. Even though the user hits the '/' endpoint, the Login Screen should be displayed instead of the Layout. -App.js <ThemeProvider theme={theme}> <Router> ...

Understanding how to utilize jQuery or prototype to interpret onclick event containing "setLocation(...)" can enhance the functionality

I am dealing with a specific tag: <button onclick="setLocation('http://mysite.com/checkout/cart/add/product/17/')" /> My goal is to trigger an ajax request when the button is clicked. I want to extract the URL segment "product/17" and app ...

Injecting multiple instances of an abstract service in Angular can be achieved using the following techniques

I am fairly new to Angular and currently trying to make sense of the code written by a more experienced developer. Please excuse me if I'm not adhering to the standard communication practices and vocabulary. There is an abstract class called abstract ...

What is the advantage of using multiple states compared to a single state object in React?

When working with a functional component that requires the use and manipulation of multiple state items, I often find myself in a dilemma. Should I group all the states together in one object and set them with one method, or should I declare and set each s ...

Filter ng-repeat using OR condition for property

I'm trying to filter a list based on a model value entered in a text box. For example: var person={}; person.Id=1; person.Name="Test 1"; person.PetName="Rest 1" var persons=[]; persons.push(person); person.Id=2; person.Name="Test ds"; per ...

Revamping HTML Label 'for' with JavaScript: Unveiling Effective Techniques

I'm facing an issue with changing the target of a label that is associated with a checkbox using JavaScript. Here's the code I have: <input type="checkbox" id="greatId" name="greatId"> <label id="checkLabel" for="greatId">Check Box&l ...

The issue with launching a Node.js server in a production environment

I'm currently facing an issue when trying to start my TypeScript app after transpiling it to JavaScript. Here is my tsconfig: { "compilerOptions": { "module": "NodeNext", "moduleResolution": "NodeNext", "baseUrl": "src", "target": " ...

What is the best way to enclose a block of content with <div> and </div> tags using the append() function?

My goal is to add an outer div container by first appending it, then adding content, and finally appending the closing tag. However, I'm encountering an issue where the div I added at the beginning automatically closes itself, resulting in two separat ...

Tips for executing a function on a specific class selector using the document.getElementsByClassName method

When I click on a specific class, I want to implement a fade-out function in JavaScript. However, I am struggling to make a particular class fade out successfully. I attempted to use the this keyword, but it seems like I might be using it incorrectly bec ...