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

Executing a method to retrieve a value from an empty function in Node.js

I am currently dealing with the code snippet below: function done(err, file) { //handling of code here return "test"; } function process() { retext() .use(keywords) .process(sentence, done); return val; } The proce ...

Encountering issues with importing a module from a .ts file

Although I have experience building reactJS projects in the past, this time I decided to use Node for a specific task that required running a command from the command line. However, I am currently facing difficulties with importing functions from other fil ...

The function of style.marginRight differs from that of style.marginLeft

One function aligns content to the left while the other doesn't align it to the right function openNavLeft() { document.getElementById("mySidenavLeft").style.width = "100vw"; document.getElementById("main").style.marginLeft = "100vw"; } function ...

How can I trigger a CSS animation to replay each time a button is clicked, without relying on a timeout function?

I am having trouble getting a button to trigger an animation. Currently, the animation only plays once when the page is refreshed and doesn't repeat on subsequent clicks of the button. function initiateAnimation(el){ document.getElementById("anima ...

Analyzing arrays and object key/value pairs based on a specific value in javascript

I want to create a new object with key/value pairs. The new object should include values from an existing key/value object as well as unique values from an array. Here is the array: [{ name: "Computer", name: "Car", name: "House&q ...

Using vanilla JavaScript in a node.js environment alongside Functional Reactive Programming (FRP) with bacon.js

I am interested in incorporating Functional Reactive Programming (FRP) into my project. I have come across a popular library for node.js called bacon.js that implements FRP. However, I am having trouble finding examples of how to use bacon.js in native J ...

Angular Unit Testing: Executing Multiple expectGET's within a Singular Test

I am facing an issue with a unit test that fails to read the JSON in the second request properly This is my implementation of the Config factory (function() { 'use strict'; angular.module('commercial.factories').factory(&apos ...

Having trouble uploading several files with Multer functionality?

I've encountered an issue with Multer in Node.js where I can't seem to select and upload multiple files. In a previous exercise, I had no trouble uploading a single file, but now I'm struggling with enabling multiple uploads. What am I mis ...

Maximizing the potential of process.hrtime.bigint

Whenever I include the following code: const a = process.hrtime.bigint(); The linter says it's okay, but during compilation, I encounter this error message: error TS2339: Property 'bigint' does not exist on type 'HRTime'. This ...

Using rxjs for exponential backoff strategy

Exploring the Angular 7 documentation, I came across a practical example showcasing the usage of rxjs Observables to implement an exponential backoff strategy for an AJAX request: import { pipe, range, timer, zip } from 'rxjs'; import { ajax } f ...

Try utilizing the array find() method in place of a traditional for loop

Is there a better way to refactor this code using the Array.find() method instead of nested for loops? onLoadTickets() { const ticketsReq = this.ticketService.getTickets(); const tariffsReq = this.tariffService.getTariffs(); forkJoin([ticketsR ...

Axios and Postman generate unique X-CSRF tokens

Why does the X-CSRF token I receive from my axios request differ from the one I get in Postman? Here is how I am retrieving it: headers: { "X-CSRF-Token": "FETCH" } Furthermore, I am unable to use the X-CSRF token from my axios request in Postman as it ...

Mastering the art of effectively capturing and incorporating error data

Is there a way to retain and add information to an Error object in typescript/javascript without losing the existing details? Currently, I handle it like this: try { // code that may throw an error } catch (e) { throw new Error(`Error while process ...

Incorrect ng-pattern does not enable the tooltip to be activated

I have implemented the ng-pattern="/^[0-9]{9}$/" in an input field that appears as follows: <input type="text" id="company_taxId" ng-model="company.taxId" required="required" class="input ng-scope ng-valid-maxlength ng-valid-mi ...

What is causing my AJAX Contact Form to navigate away from the original page?

I configured a contact form on my website more than 5 years ago, and I vividly remember that it used to show error/success messages directly on the page within the #form-messages div. However, recently, instead of staying on the contact form page and displ ...

Pull the Bootstrap radio value from hyperlink buttons

Is anyone else having trouble retrieving values of radio buttons using jQuery? Here are the radio buttons in question: <div class="input-group"> <div id="radioBtn" class="btn-group"> <a class="btn btn-warning radio-selector btn ...

"What is the best way to access the value of a useState variable in ReactJS on a global

Below is my reactJS code snippet - useEffect(()=>{ const getinterviewerDetails= async ()=>{ const data1 = await axios.get("http://localhost:8083/api/GetProduct") .then(response => { console.log("role is " ...

Vuex getters not displaying expected values in computed properties until entire page has finished loading

When working with computed properties using data fetched by the mapGetters function in my Vuex store, I always encounter the issue of getting an undefined value until the entire page or DOM is fully loaded. For instance, I have an example of an isRegister ...

Various results can be produced based on the .load() and .resize() or .scroll() functions despite using the same calculation methods

I'm currently working on developing my own custom lightbox script, but I've hit a roadblock. For centering the wrapper div, I've utilized position: absolute and specified top / left positions by performing calculations... top: _center_ver ...

What is the method in AngularJS2 for using TypeScript to inject dependencies into components?

I have been encountering different methods of injecting dependencies into my component and not all of them seem to be working for me. I am curious about the advantages and disadvantages, what the recommended best practices are, and why some methods are not ...