Chai's rejectedWith method fails to properly chain

After reviewing various posts and documentation, I am struggling to understand why this code is not functioning as expected.

const chai = require('chai');
const expect = chai.expect;
const chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

async function foo(val) {

    if (!val) {
        const err = new Error();
        err.status = 404;
        throw err;
    }

    return new Promise(resolve => sleepSetTimeout_ctrl = setTimeout(resolve, 10));
}

describe('does not work', () => {
    it('throws', async () => {
        await expect(foo()).to.be.rejectedWith(Error).and.have.property('status');
    });
});

When I stop the expect at rejectedWith(Error), everything works fine. However, when trying to test for the existence of a property, it fails with:

AssertionError: expected {} to have property 'status'

Answer №1

The reason behind this is that when you use the rejectedWith method, it returns a PromisedAssertion, which checks if the promise-like object has a status property. A more detailed error message can help clarify this:

AssertionError: expected Promise{…} to have property 'status'

If you want to test for a property that the object does have, such as then:

await expect(foo()).to.be.rejectedWith(Error).and.have.property('then');  // ✅

To assert on the actual error object, you will need to utilize chainers from chai-as-promised once again, like this:

await expect(foo()).to.be.rejectedWith(Error).and.eventually.have.property("status");  // ✅
                                              // ^---------^

Alternatively, if you have multiple assertions to make on the resolved or rejected value, you can chain using .then:

await expect(foo()).to.be.rejectedWith(Error).then((err) => {
    expect(err).to.have.property("status", 404);
}); // ✅

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

Having trouble adding elements (after the initial iteration) using the push() method in JavaScript

I'm facing an issue where I have a string and an array, but I'm unable to push elements after the first iteration. Below is the code I'm using: response1 = "hello"; var arr = [""]; arr.push(response1); console.log("First position " + arr[0 ...

Analyzing User Input and Database Information with Mongodb

Here's the HTML form I'm working with: <form id="contact-form" method="POST" action="/search"> <label for="company">Phone company</label> <input type="text" name="company" value=""> &l ...

Is there a way to make a picture fill the entire background?

Is there a way to make pictures expand across an entire page with different resolutions? I'm trying to achieve this effect but unsure how. Take a look at my current example: . ...

How can I permanently disable a Bootstrap button on the server side using PHP after it has been clicked once?

I am in search of a way to disable a bootstrap button permanently after it has been clicked once. While I am aware of how to achieve this on the client side using JavaScript, the button becomes enabled again after the page is refreshed. I am now looking ...

Transferring Information between JavaScript and Python

How can I efficiently transfer data received in JavaScript to a Python program for processing? The data arrives as a string in JavaScript on my browser, but my Python program requires this string to perform specific tasks. What is the best way to pass the ...

React error: The dispatch function is not defined

I'm trying to retrieve data from redux by following this tutorial: https://codesandbox.io/s/react-redux-application-hewdb?file=/src/pages/PostsPage.js However, when I implemented it in my code: import React, { useState, useEffect } from 'react& ...

Does the directive lack access to transcluded elements?

I seem to be missing something here, as I can't seem to get the desired outcome with my code: http://plnkr.co/edit/Qe2IzMMMR5BJZJpwkx9e?p=preview My goal is to create a directive that can be applied to a top-level <nav> element, and then manipu ...

JavaScript post method for JSON data: no input or output values

I am currently developing a page that extracts data from an HTML table consisting of two columns and an index of a form, and then converts it into a JSON string. The intention is to pass this data into PHP for further processing, perform calculations on th ...

I am looking for a unique array that is distinct and can be used in a reusable function

I'm struggling to create a unique array using this function. ---Here is the Function I'm Working With--- var Array = [2, 0, 1, 9, 1, 3, 2, 4, 5, 5, 3, 4] function uniqueArrayValues(val){ var newArray=[]; for(var i=0 ; i < val.length ...

What are the best practices for managing methods in asynchronous programming with the use of node.js, Ajax, and MySQL?

I have a query regarding the handling of methods using Node.JS, ajax, and mysql in the provided code snippet. When the client enters the correct username and password, the server should return a "true" value to my front-end (index.html) and redirect to th ...

Tips for displaying an entire division without altering the position of its content

I am looking to create a pop-up effect for the entire div that includes images, text, and more. However, I have encountered an issue where when I activate the pop-up feature, the position of the content within the div changes. My goal is to have the div zo ...

Challenges with transitioning to IE 11

During the process of moving our application from IE 8 to IE 11, we encountered an unexpected problem. The following jQuery code that functioned properly in IE8 is failing to work in IE11. $("#Submit").attr("disabled", "disabled"); Is there anyone who ca ...

Retrieve an array of objects using URLSearchParams

I am in need of extracting the array of objects named filter from a URL string: http://localhost:3006/menus?page=1&filter[0][id]=MenuID&filter[0][value]=2&filter[1][id]=ParentMenuName&filter[1][value]=u. This is my current approach: con ...

Trigger ng-change in AngularJS when modifying a data model

I designed a form that has the following structure: <div class="col-xs-12 col-lg-4"> <form name="deliveryForm" ng-class="{ 'has-error': deliveryForm.$invalid && !deliveryForm.contact.$pristine }"> <div class="f ...

I'm having trouble getting the drag event to work for Three.js trackball controls within a UIkit

The issue at hand involves a fullscreen Three.js canvas that is functioning perfectly, but there are limitations when displaying a preview in a UIkit modal – zooming works, but panning does not. JS: Renderer and Controls renderer = new THREE.WebGLRende ...

Execute a function only once

Is there a way to call and utilize this function just once, and then terminate it? When calling the function: else if (msg.text == [" ...

Connecting prop variables to component variables establishes a direct relationship between them

By assigning the props variable to a component variable, any changes made to the component variable will also reflect in the props... Parent Component: const prova = [ { 1: 'a' }, { 2: 'b' }, { ...

Using the Vue.js Compositions API to handle multiple API requests with a promise when the component is mounted

I have a task that requires me to make requests to 4 different places in the onmounted function using the composition api. I want to send these requests simultaneously with promises for better performance. Can anyone guide me on how to achieve this effic ...

Looking to locate an array within a schema using its unique identifier

const FormFieldsSchema = new Schema({ formName: { type: String, required: true }, fields: [ { fieldLabel: { type: String, required: true }, inputData: [{ type: mongoose.Schema.ObjectId, re ...

Give an npm package a nickname using a browserify shim

I'm in the process of transitioning from requirejs to browserify. One of the dependencies I have is for masonry. Trying to shim it using the bower version was proving to be a little challenging (more on that can be found here). Instead, I decided t ...