What is the best way to test for errors thrown by async functions using chai or chai-as-promised?

Below is the function in question:

async foo() : Promise<Object> { 
   if(...) throw new Error
}

I'm wondering how I should go about testing whether the error is thrown. This is my current approach:

it("checking for thrown error", async function () {
   expect(async() => await foo()).to.throw(Error)
})

Answer №1

If you utilize a structure similar to this one and an error arises, the test will not pass.

const bar = async (): Promise<Object> => {
  // To fail the test, modify y to be greater than 10
  const y = 0
  if (y > 10) {
    throw Error('Test unsuccessful')
  }
  // Insert relevant code; the following is merely an illustration
  return { another: 'example' }
}

it('checking for raised error', async () => {
  const objectTwo = await bar()
  expect(objectTwo).toEqual({ another: 'example' })
})

Answer №2

Give this a shot:

it("checking if an error is thrown", async function () {
   await expect(myFunction()).rejects.toThrow(Error)
})

Answer №3

When discussing chai-as-promised, there are two ways you can handle it:

expect(promise).to.eventually.be.rejected

or:

promise.should.be.rejected

If needed, you can also use rejectedWith() to specify the Error class/constructor.

Here's a demonstration:

mocha.setup('bdd');
mocha.checkLeaks();

let { expect } = chai;
chai.should();
let chaiAsPromised = module.exports; /* workaround for lack of UMD file, only for SO */
chai.use(chaiAsPromised);

async function foo(){ 
   throw new Error();
}

describe('Asynchronous Function', function(){
  it('Expect and Eventually', function(){
      return expect(foo()).to.eventually.be.rejected;
  })
  
  it('With Should', function(){
      return foo().should.be.rejected;
  });
});

mocha.run();
.as-console {
   display: none !important;
}
<script>
window.module = {}; function require(){ return {} }; /* workaround for lack of UMD file, only for SO */
</script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98fbf0f9f1b5f9ebb5e8eaf7f5f1ebfdfcd8afb6a9b6a9">[email protected]</a>/lib/chai-as-promised.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/9.1.1/mocha.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="204348414960140e130e14">[email protected]</a>/chai.js"></script>
<link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
<div id="mocha"></div>

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

The transition from material-ui v3 to v4 results in a redux form Field component error stating 'invalid prop component.'

Since upgrading from material-ui v3 to v4, I am encountering an error with all my <Field> components that have the component prop. Error: Warning: Failed prop type: Invalid prop component supplied to Field. The Field component is imported from im ...

Filter an array in Angular 2 and add additional data to it

Quick query: I have 2 arrays/objects. The first one contains all items, while the second contains selected IDs from the first array. My question is, what is the most efficient way to iterate through both arrays, identify selected items from the second arr ...

Why isn't Material UI Data Grid onCellEditCommit working? Wondering if anyone has insight

Having trouble retrieving the data after editing using onCellEditCommit, but it's not functioning properly. This callback is triggered when changes to a cell are committed. Signature: function(params: GridCellEditCommitParams, event: MuiEvent, deta ...

Enrollment of Vue components

After importing the component into the JavaScript file, I added it to the index.vue file as follows: import fmsSubUnitDetails from '../subunitDetails'; export default{ components: { fmsSubUnitDetails }, } Despite this, I am still encount ...

Engage with and rearrange JSON data

Upon receiving data from the endpoint, I realized that it needed some modifications before being suitable for display in a table. The initial example data looks like this: const data = [ { Year: 2017, OriginalIntBalanceOverdue: 0.0, D ...

Tips for sending a form using Angular 1.5.8 and Java Servlet via POST method

After reading various tutorials and online documentation, I'm still struggling to figure out how to pass parameters from a JSP form. Below is the JavaScript script I am using: var app = angular.module('myApp', []); app.controller('Form ...

Angular unable to retrieve data using Angularfire2

Having trouble retrieving data from the Real time Database on firebase. Read and Write permissions are set to public so no authentication is needed. The npm compilation is successful, indicating that the Angular-CLI code is correct. Following the document ...

Unable to close window with window.close() method after initially opening it with JS or JQuery

I am currently using an Instagram API that requires users to log out through the link . This link redirects users to the Instagram page, but I want them to be redirected to my own page instead. Although I tried different methods from a previous post on thi ...

Executing Actions Prior to Redirecting

I am working on implementing a timer process using a custom JQuery plugin that will redirect to the login page after a specific number of minutes. Additionally, when the timer reaches zero, I need to execute a task, which in this case involves making a cal ...

utilize jQuery and AngularJS to transform a JSON object into a nested JSON structure

Is there a way to convert my current JSON file into a nested JSON structure like the one below? I've attempted various methods (How to convert form input fields to nested JSON structure using jQuery), but I'm not achieving the desired outcome. Ca ...

The dimensions of the body are set to 100vh in height and width. However, the div inside this body has a width of either 100vh or 100%, but it is not

I am trying to create a div element that has a width equal to the viewport of the browser. However, I am encountering issues when applying the CSS property width:100vh to the body element. Here is my code snippet: body { font-family: Staatliches; fo ...

Tips for simulating changing data in snapshot tests?

Two challenge are puzzling me currently: The snapshot test for a router page includes custom routers with guards specifically for logged in users. Each time I run this test, a different generated key is produced. I am using new Date() in a date pick ...

Cross-Domain Image Uploading

I've been attempting to enable image uploads from one domain to another (CORS). Everything runs smoothly on Localhost, but when I try it on an actual domain, I consistently encounter this message in the Developer Console: Invalid request In my uplo ...

Using Typescript to specify the parameter type of a function as a generic function

After creating a function called compose, it looks like this: const composeTyped = <T, U, R>(f: (x: T) => U, g: (y: U) => R) => (x: T) => g(f(x)); It appears to me that both functions f and g fall under the type fGeneric, which is define ...

Is it possible to personalize Carousel-indicators within react-bootstrap?

I'm currently utilizing the Carousel component from . My goal is to customize the carousel-indicators, adding text and making them appear as buttons with text. However, when I attempt to do so, React renders 'ol' tag into a new CarouselItem ...

Conceal a script-generated div using CSS styling

Using the code below, you can create an HTML chatbox with a link in the top panel and multiple child divs. The structure is as follows: cgroup is the parent of CBG, which is the parent of CGW, and CGW is the parent of the div I want to hide. How can I u ...

What could be causing the VueJS function not to be triggered by the dropdown selection?

I created a simple component called LocaleSwitcher.vue using the Element UI library: <template> <el-dropdown trigger="click"> <div> <i class="el-icon-map-location"></i> </div> < ...

Is it possible to create a function that only accepts a union type if it includes a specific subtype within it?

Is there a way to define the function processArray so that it can handle arrays of type string[], without explicitly mentioning individual types like type1 or type2? For instance, could we indicate this by using arr: type1 | type2? The objective here is t ...

if and elsif JSON with Angular

Currently, I am working on completing a task within our project. To provide more context, I have a field with items that I must select. Once I choose an item, another field appears in which I must select additional elements. These elements need to be sen ...

Accessing dropdown selection in Javascript-Json: A Comprehensive Guide

My dropdown list is being populated dynamically using json. The selected option from the first dropdown determines the options in a secondary dropdown. I need to use the selection from the second dropdown to automatically fill out two more fields. For exa ...