Mocha throws an unexpected AssertionError that is not being handled

I have encountered an error while writing a Mocha test for a module in my express application. I am unsure about how to resolve this issue.

Here is the test:

  describe('userController', function() {
    describe('post -> /create', function() {
      it('A user should be created', () => {
          var testRequest = {
              body: {
                  password:"pass1",
                  email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea9e8f999eaa87fc4898587">[email protected]</a>",
                  username:"user1",
              }
          };
          database.registerUser(testRequest, (callBack) => {
              new User({email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a5b4a2a591bcb4ffb2bebc">[email protected]</a>"})
              .fetch()
              .then((model) => {
                 assert.equal(model.get('password'), testRequest.body.password);
              })
              .catch((err) => {
                assert(false);
              });
          });
      });
    });
  });

The Error:

Unhandled rejection AssertionError: false == true
    at User.fetch.then.catch (/home/shanedrafahl/code/MyRentalServer/myRental/test/test.js:72:17)
    at tryCatcher (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/promise.js:689:18)
    at Async._drainQueue (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/async.js:133:16)
    at Async._drainQueues (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:672:20)
    at tryOnImmediate (timers.js:645:5)
    at processImmediate [as _immediateCallback] (timers.js:617:5)

I would appreciate any guidance or insight on why this error is occurring and how I can resolve it.

Answer №1

It appears there are two issues at play here. The first being the actual problem you are facing, and the second being related to the test itself. Perhaps tackling the test problem first could shed light on how to approach solving the primary issue.

While I may not be well-versed in the workings of assert, based on the stack trace provided, it seems that you are anticipating assert to perform differently in this particular section:

.catch((err) => {
  assert(false);    // <---- the issue lies in the first parameter being false
});

Resolution (for the test problem)

It seems that what you actually intend to do is to output the contents of err. This could help in understanding the reason why you are encountering the catch block in the first place.

Given that your test is asynchronous, it might be beneficial to utilize done as shown below:

it('A user should be created', (done) => {  //added done parameter

...

.then((model) => {
  assert.equal(model.get('password'), testRequest.body.password);
  done() // signaling Mocha that the async test is completed
})
.catch((err) => {
  done(err) // notifying Mocha that the async test is finished with an error, allowing the error to be displayed in the output
});

By following these steps, you should be able to proceed with testing your code effectively, pinpointing the root cause of the underlying issue.

For further insights on asynchronous testing with Mocha, you can refer to the documentationhere: Mocha - Asynchronous Code

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 interactions and functionalities of jQuery sortable and draggable elements

Looking for some assistance with a project involving draggable objects 'field' and 'container', along with a sortable object 'ui-main'. The goal is to drag the two aforementioned objects into 'ui-main', while also al ...

Switch button - reveal/conceal details

I am looking for assistance in toggling the visibility of information when clicking on an arrow icon. I have attempted to use JavaScript, but it was unsuccessful. My goal is to hide the information below by clicking on the downward-facing arrow image , an ...

Unable to transmit information using Postman for registration API

I have been struggling to send data via a POST request to the register API, but for some reason, the data is not being transmitted. I have tried adjusting the settings on Postman, tinkering with validation rules, and various other troubleshooting steps, ye ...

Is the Facebook AJAX Permissions Dialog displayed outside of a Pop-Up?

I have conducted extensive research but have failed to find a clear answer to my query. Although there is plentiful information on Facebook API AJAX/PHP communication, I am unable to locate an example where the Permission Dialog for an app (showPermissionD ...

Is it possible to transfer a variable from my javascript code to a jsp file?

Within a HTML file, I have created a variable in JavaScript consisting of an array with two entries - a latitude and a longitude. I am looking to use AJAX to send this variable and then utilize it in my JSP file to populate a form. Does anyone have any su ...

Move files into the designated folder and bundle them together before publishing

Is there a way to transfer the files listed in package.json (under the File field) to a specific folder in order to bundle them together with npm publish? Here is the structure of my repository: . ├── package.json └── folder0 ├── fil ...

Identifying when a user is idle on the browser

My current project involves developing an internal business application that requires tracking the time spent by users on a specific task. While users may access additional pages or documents for information while filling out a form, accurately monitoring ...

Using Highcharts to dynamically color a map based on data values in a React TypeScript project

I'm attempting to generate a map where each country is filled with colors based on its specific data, similar to the example shown in this map. I am looking for a functionality akin to the use of the formatter function within the tooltip. I have expe ...

Clicking again on the second onclick attribute

I have an image file named image1.png. When the button is clicked for the first time, I want it to change to image2.png. Then, when the button is clicked for a second time, I want it to change to yet another image, image3.png. So far, I've successful ...

The conditional statement is failing to execute properly in the JavaScript AJAX response

When checking the value in the alert, it always shows as 'Initial'. However, the condition if(checkoption == 'Initial') always returns false. The actual code is as follows: function changeItem(id,item,option) { var xhttp; xht ...

Is it a Mozilla Firefox glitch or something else?

After writing the code, I noticed a bug in Firefox and a small bug in Chrome. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> ...

straightforward multiple second timer

I have multiple <span class="timer">342</span> elements with different values (in seconds). I am trying to create a countdown timer for all of them by using the following code: $('.timer').ready(function() { ...

What steps can be taken to update the cart if all products have been removed?

How can I implement a refresh for my cart page every time the product length is 0 without causing unreachable code? It seems like there must be a simple solution to this problem. switch (action.type){ case "REMOVE_PRODUCT": return ...

Hover over the text to disable the input element and display it as a textbox

Currently, I have a situation where I have two text boxes - when text is entered into textbox1, textbox2 becomes disabled as expected. However, my second requirement is that upon disabling textbox2, hovering over it should display the message "You can ente ...

Issue: The handlebars error states that the partials directory must be specified as a string or a configuration object

When attempting to send templated emails using nodemailer with nodemailer-express-handlebars, I keep encountering the following error message: Error: A partials dir must be a string or config object. I am unsure of what is causing this issue. const expr ...

Is there a way to create an image gallery layout similar to Pinterest using CSS?

I am currently developing a dynamic PHP gallery that will feature thumbnails with the same width but varying heights. These thumbnails will be arranged from left to right, so I would prefer not to use a traditional five-column layout. I suspect that achiev ...

Checking for correct format of date in DD/MM/YYYY using javascript

My JavaScript code is not validating the date properly in my XHTML form. It keeps flagging every date as invalid. Can someone help me figure out what I'm missing? Any assistance would be greatly appreciated. Thank you! function validateForm(form) { ...

Angular's scope allows for the application of CSS classes exclusively to the first div element

Every 2 seconds, a JavaScript function is being called that updates a specific div on the view when a certain condition is met. <div id="ball_{{ballIndex}}">{{ball}}</div> This is controlled by the ng controller. var myCounter = 0; ...

What is the process for reverting back to a previous version using n (Node Version Manager)?

After installing n(tj/n) to manage my node versions, I installed Node version 14.6 which automatically became the active version. When I tried to switch back using the n command, it only displayed the version I installed with n. Is there a way to switch b ...

Does a Lambda function with Express reload its middleware for every request?

Summary: Does the middleware called by app.use in Express get recalculated for each request? In my Lambda function, I have implemented a middleware that adds the user to every request: async function(req, res, next) { try { const IDP_REGEX = /.*&bs ...