Using assert.rejects() in Mocha and Node: A Complete Guide

Following the instructions in the documentation, I attempted to use assert.rejects to test for an error message (I have Node version above v10).

However, no matter what message I specify, the test always passes. What could be causing this issue?

it("is failing when it should not", 
  async ()=> {
    let itemId = 'not an id'
    assert.rejects( 
      await ListRepo.checkById(itemId),
      {message: 'abracadabra'}                        
    )
  }
)

UPDATE: It appears that returning the assert.rejects statement solves the problem, although the reason remains unknown.

Answer №1

After careful consideration, I have come to the realization that while the information provided above is accurate, it can be simplified for better understanding. It is indeed crucial to return a promise in order for Mocha to have something to wait for, preventing it from returning prematurely before the promise resolves or rejects. However, manually waiting for a promise may not always be the most efficient approach.

A more straightforward pattern suggested by @caub involves awaiting the promise returned by assert.rejects. To implement this pattern:

it("should fail but it's not", 
  async () => {
    let itemId = 'not an id'
    await assert.rejects( 
      ListRepo.checkById(itemId),
      {message: 'abracadabra'}                        
    )
  }
)

There are three key points to note here:

  1. The test function itself must be marked as async.
  2. Use await with the assert.rejects call inside the async test function. This automatically ensures that the test function returns a Promise<void>, streamlining the process and enabling easy reuse of the assert call in other parts of the codebase.
  3. Avoid using await on the value passed into the rejects call. The input should be a promise, not an awaited value.

Answer №2

What nicholaswmin mentioned is indeed accurate, however, there is a crucial "rest of the owl" moment that I would like to clarify.

If you are thinking: "I want to ensure rejection," meaning "I want to verify that this code rejects correctly," the process is a bit intricate.

To begin with, include return fxnWhichReturnsPromise(). The test will not pass if your function is rejecting, and you actually want it to fail under those circumstances. You must utilize the two-argument form of .then(), which appears as follows:

.then(onFulfillCallback, onRejectCallback)
. This is necessary because if you separate it into .then and .catch, failing in the .then block will be captured by the subsequent .catch block. Consequently, what should be a failed test (as it did not reject) will actually show as passing.

In practical application, the whole setup looks similar to this:

it('rejects when given foobar', () => {
  return fxnThatShouldReject(foobar)
    .then(
      (val) => { assert.fail(`Should have rejected, but instead returned ${val}`)
      ,
      (err) => { assert.equal(err.message, "The expected reason for rejection") }
    )
}) 

The reason why the assertion library lacks a pre-defined handler for this scenario is because being able to temporarily pause asynchronous execution within the test suite is essentially a feature of the test-runner. In contrast, assert.throws() operates synchronously.

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

Accessing elements within a ReactJS map structure using the material-ui Selectable List component is not supported

I'm facing a dilemma. Unfortunately, my proficiency in English writing is not up to par... ※Please bear with me as it might be hard to follow. I'm trying to choose the ListItem component, but for some reason, I can't select the ListIt ...

Anchoring HTTP headers in HTML tags

Currently, I am working on some code to enable dragging files from a web app to the desktop by utilizing Chrome's anchor element dragging support. The challenge I am facing is that certain file links require more than a simple GET request - they nece ...

What is the best way to activate a JavaScript function once a page has finished loading?

Hey there! I have a webpage with 2 text input fields and a DIV element. The first input field is for user input, while the second one is readonly. When the user hits Enter in the first input field, a new page loads into the DIV based on the query result f ...

Developing a jsp page with interconnected drop down menus

I am looking to dynamically populate the options in a second drop-down based on the selection made in the first drop-down. For instance, if I have a first drop-down with options {India, South Africa, USA}, and I choose India, then the second drop-down shou ...

What is the best way to create three buttons for selecting various parameters?

I have a code snippet where I want to assign different parameters to each button when clicked. However, despite my logic, the functionality is not working as expected. Can someone help me with the correct syntax? For example, if I click the "Start (Easy) ...

Enhancing Animation Speed with jQuery

I've provided the code snippet at this link: http://jsfiddle.net/LnWRL/4/: Here is the HTML: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> <div id="wrap_demo"> <div id="demo"></di ...

React Navigation Item Toolbar Misplacement

I've been trying to align the navigation item with the logo on the same line within the toolbar, but I'm facing an issue where they keep appearing in different rows. To see the error for yourself, check out the code sandbox here. This is how I s ...

ReactJS encountered an error of type ERR_INVALID_ARG_TYPE

Hello there! I recently purchased a template from ThemeForest and everything was working perfectly with the previous version. However, upon updating to the new version, I encountered an error that looks like this: > TypeError [ERR_INVALID_ARG_TYPE]: Th ...

fnRedraw and fnReloadAjax do not have the capability to refresh the datatable

I have been working on updating a table with new data from an ajax url. The table loads correctly the first time, but I am struggling to get it to refresh. $(function() { var datepicker = $( "#date-picker" ); var table = $("#reports1").dataTable( ...

Implementation issue with Hashids library in Vue.js causing functionality hiccups

I'm having trouble getting the library hashids to cooperate with vue.js The method I would like to use is: <template> <div class="container"> {{ hashids.encode('1') }} </div> </template> <script& ...

Displaying a hand cursor on a bar chart when hovered over in c3.js

When using pie charts in c3js, a hand cursor (pointer) is displayed by default when hovering over a pie slice. I am looking to achieve the same behavior for each bar in a bar chart. How can this be done? I attempted the CSS below, but it resulted in the h ...

Maintain checkbox selection even after the page is refreshed

Having trouble fetching all objects from the favorites array and setting the checkbox to checked. I've attempted using localStorage but the values are not saved after refreshing, despite researching online for solutions. Any assistance would be great ...

Am I on the right track with incorporating responsiveness in my React development practices?

Seeking advice on creating a responsive page with React components. I am currently using window.matchMedia to match media queries and re-rendering every time the window size is set or changes. function reportWindowSize() { let isPhone = window.matchMed ...

What could be causing my Bootstrap modal to fail to load dynamically?

I'm currently immersed in a fun side project, where data is fetched from a MySQL database and dynamically displayed. Everything seems to be running smoothly except for the modal display issue. The ID always matches, but the modal just won't open. ...

Tips for displaying the sum of a grouped field in the balloonText using Amchart

I recently started working with Amcharts and I am seeking advice on what I may be doing incorrectly. Below is the snippet of my JavaScript code: var chartData1 = []; generateChartData(); function generateChartData() { var month = new Array( ...

Ways to efficiently display elements in a grid in real-time

Attempting to design a layout where each row consists of 3 cards using Bootstrap's Grid layout for responsiveness. The challenge lies in the fact that the card data is stored in JSON format, and the length of the JSON Object array may vary, leading t ...

The Chrome developer tools are unable to locate the HttpRequest

While working in Python, I am utilizing the requests library to make a POST request to a specific URL. However, upon clicking the button, it seems that nothing is happening as per Chrome Developer Tools. No XHR requests are being made and no data is being ...

Best Practices for Making Remote Requests in Ruby on Rails

Currently, I am creating a Single Page Application using Ruby on Rails for the first time. Although I am still learning, I have set up a side menu with links and a container on the right part of the page to display partial pages. An example of one of my me ...

JavaScript: function that operates asynchronously

I am new to JavaScript and encountered some issues with async functions. I have a function that fetches data from MongoDB by creating a promise, but it returns a collection with an empty object. async function getRating(item, applicant) { let arr = await ...

switching the image source by selecting different options from a dropdown menu and leveraging JavaScript

I have been attempting to change the src of an image using JavaScript's addEventListener, but for some reason it is not working. Here is an example to illustrate my issue: let bulbImage = $.querySelector(".bulb-image"); let turnOnOption = $.querySele ...