Chai encountering issue with async/await when parameter is not provided

When testing my Typescript code, I encountered an issue where it should throw an error when no parameter is passed.

getID(ID) { if(!ID){throw new Error('stop js')} ....}

it('should fail if no ID', async () => { 

    expect(async () =>  await myService.getID() ).to.throw("stop js");
})

Even though the documentation suggests that the above code should work as expected, when running the test, I received this error message:

 1) myTest
   should fail if no groupId is passed:
 AssertionError: expected [Function] to throw an error

Answer №1

Working with Promises involves using asynchronous operations; async/await is simply a more concise way to work with Promises.

For example, in the code snippet below:

it('should fail if no ID', () => { 
    expect(/* not async */ myService.getID()).to.throw("stop js");
});

The getID function will synchronously throw an Error. However, in this code snippet:

it('should fail if no ID', async () => { 
    expect(async () =>  await myService.getID()).to.throw("stop js");
});

The async keyword will pass a Promise into expect, resulting in an asynchronous rejection with the specified Error message.

To simplify working with Promises, consider using the library chai-as-promised:

return expect(async () => await myService.getID()).to.eventually.throw("stop js");
// or
return expect(async () => await myService.getID()).to.eventually.be.rejectedWith("stop js");

Remember to either return the result of expect or use await to ensure that your test waits for the expect result before proceeding.

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

Transitioning the height of a Vue component when switching routes

I've been struggling to implement a transition slide effect on my hero section. The height of the hero is set to 100vh on the homepage and half of that on other pages. Despite trying various methods, I haven't been able to get it working properly ...

An excellent user interface that enables the user to easily reset a field to its original default value

Within my web-based application, users have the ability to customize values in specific textboxes. If they choose not to customize a value, the system will default to a predetermined option. I am looking to incorporate a feature that allows users to easil ...

Is it possible to add a new document or parameter to the user.profile from the client in Meteor.js and Mongo?

Is it possible to insert an array of a user's links into the current user's profile? I attempted the following on the client side, but it did not work: Meteor.users.update( {_id: Meteor.userId()}, { $set: { profile: { ...

What is the best way to pass the values of two interlinked drop-down menus through an AJAX post request to a Django view?

Presently, I am encountering an issue with sending the values of two dropdowns to a django view. My code would have functioned correctly if the dropdowns were independent. Unfortunately, this is not the case as the first one updates the second one. Therefo ...

Challenges encountered while formatting Json strings for WCF service transmission

I need assistance in connecting a JavaScript application to a WCF service. The WCF Service I have includes the following method: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFor ...

Improving the configuration of fetching data using the useEffect hook

As I continue my journey in learning JavaScript and React, I've encountered the following code example that has left me with some lingering questions. One particular area that puzzles me is the positioning of the second .then inside the useEffect func ...

I am having success posting data through a form, however, the fetch API is not functioning as expected for me

Currently, I am working on a React Project and focusing on creating a signup form. Everything seems to be fine when posting form data using the Form, but things get stuck when I try to use onSubmit={handleSubmit} along with fetch APIs such as axios or just ...

Filtering data within a specific date range on an HTML table using JavaScript

I am attempting to implement a date filtering feature on my HTML table. Users should be able to input two dates (From and To) and the data in the "Date Column" of the table will be filtered accordingly. The inputs on the page are: <input type="date" i ...

The 'Key' identifier is not valid for indexing the 'Object' data type

Currently attempting to incorporate functional pluck with a specific sound type, but encountering an issue: function extract<Object extends {}, Key = keyof Object>(key: Key): (o: Object) => Object[Key] { return object => object[key]; } Erro ...

Building a structured array from nested JSON data using JavaScript

[ { "item": "1", "values": [{"name": "A"}] }, { "item": "2", "values": [{"name": "B"}] }, { "item": "3", "values": [{"name": "A"}] } ] The desired outcome is to extract ["A", "B"] bas ...

What is the most efficient way to remove all typed characters from fields when clicking on a different radio button? The majority of my fields share the same ngModel on a separate page

Is there a way to automatically clear all typed characters in form fields when switching between radio buttons with the same ngModel on different pages? I noticed that the characters I type in one field are retained when I switch to another radio button. ...

execute an action in the controller with the help of JavaScript and refresh the view

My scenario involves having multiple selects such as brands and products. I aim to dynamically update the products options based on the brand selected by the user. The select element looks like this: <select asp-for="Product.BrandId" class=&qu ...

Refresh the table with updated results by clicking on a link

I have a table displaying user suggestions. When the user clicks "read more," an AJAX call is triggered to mark the suggestion as read in the database. Currently, I use a closed envelope icon for new suggestions and an open envelope for read suggestions. ...

Issues with rendering alpha transparency correctly in Three.js png textures can be frustrating. Sometimes, the alpha

For my project, I am working on creating a cube and applying 6 different textures to each of its faces. These textures are .png files with transparent parts. Additionally, I want to apply a color to the cube and have that color show through the transparent ...

Every time I try to upload image files to cloudinary, I encounter this frustrating error message

https://i.stack.imgur.com/kRYVZ.png The issue at hand revolves around node and the challenge of using the https module with new certificates, proving to be unsuccessful... The proposed solution is ambiguous, leaving me unsure how to proceed and resolve thi ...

Using the Single Page Application to access APIs with disabled CORS restrictions

I am developing a single-page application for my personal use. One of the main features I want to include is my calendar, along with various other content all on one page. My server is based on Node.js and creates a React-based SPA. Each React component n ...

Eliminate Video Time Indicator

Can the video progress bar be removed from this specific video player? I would like it to be integrated into the embed code that I share with others. <iframe id="hapyak-player-157199-8825" marginwidth="0" marginheight="0" frameborder="no" scrolling=" ...

How to close an iframe with javascript or jquery?

I am working with a series of iframes on my website. I am trying to figure out how to close the last iframe in the list when a button is clicked. Can someone please provide guidance on how to achieve this? Specifically, I am looking to execute a window.cl ...

Encountered an issue while trying to send an email through the Gmail API: Unfortunately, this API does not provide

I am attempting to use the Gmail API to send emails. I collect user data and convert it to a base64url string. After obtaining the raw value, I attempt to send the email using a POST request. var ss=new Buffer(message).toString('base64') var ...

Listen to Vue.js event only when it is at the top

I have developed a unique Vue component for touch screen devices that allows users to input pin codes using buttons instead of standard keyboard input. The component also features customizable key mapping, and I would like to extend its functionality to su ...