What could be the reason for the failure in my mocha/chai Error throwing test?

In my pursuit to test a simple javascript package, I encountered an issue. Despite wanting to verify if an Error is thrown during the test, it bizarrely gets marked as a failure when executed.

Here's the snippet of code in question:

var should = require('chai').should(),
    expect = require('chai').expect();

describe('#myTestSuite', function () {

    it ('should check for TypeErrors', function () {

        // Taken directly from the 'throw' section in
        // http://chaijs.com/api/bdd/
        var err = new ReferenceError('This is a bad function.');
        var fn = function () { throw err; }
        expect(fn).to.throw(ReferenceError);

    })

})

Upon running the above code, the output received is as follows:

kh:testthing khrob$ npm test

> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c38293f38382425222b0c7c627d627c">[email protected]</a> test /Users/khrob/testthing
> mocha



  #myTestSuite
    1) should check for TypeErrors


  0 passing (5ms)   1 failing

  1) #myTestSuite should check for TypeErrors:
     TypeError: object is not a function
      at Context.<anonymous> (/Users/khrob/testthing/test/index.js:10:3)
      at callFn (/Users/khrob/testthing/node_modules/mocha/lib/runnable.js:249:21)
      at Test.Runnable.run (/Users/khrob/testthing/node_modules/mocha/lib/runnable.js:242:7)
      at Runner.runTest (/Users/khrob/testthing/node_modules/mocha/lib/runner.js:373:10)
      at /Users/khrob/testthing/node_modules/mocha/lib/runner.js:451:12
      at next (/Users/khrob/testthing/node_modules/mocha/lib/runner.js:298:14)
      at /Users/khrob/testthing/node_modules/mocha/lib/runner.js:308:7
      at next (/Users/khrob/testthing/node_modules/mocha/lib/runner.js:246:23)
      at Object._onImmediate (/Users/khrob/testthing/node_modules/mocha/lib/runner.js:275:5)
      at processImmediate [as _immediateCallback] (timers.js:336:15)



npm ERR! Test failed.  See above for more details. 
npm ERR! not ok code 0

I've tried various approaches including wrapping the function inside anonymous functions as suggested in different answers but still no success in passing the test. It seems like there might be some configuration error or perhaps my understanding of pass/fail criteria for the test is off.

Any insights on this matter?

Answer №1

Here is the solution to your issue:

const assert = require('chai').assert;

It's important to realize that the function assert is not being called.

Answer №2

Found it at last!

At the very top

requirement = require('chai').expect(),

was not providing any valuable information to me. Switching it to:

chai = require('chai'),

then using the test as

chai.expect(fn).to.throw(ReferenceError);

does just what I had in mind.

Appreciate the assistance.

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

Choose ng-change within the table

I've searched everywhere for an answer to this, but I couldn't find it. I have a table that contains select and date input fields. <table id="tblCorrAction" class="table table-bordered table-striped table-hover table-condensed"> <t ...

Unable to access property 'map' of undefined - error occurred while processing JSON data in line test.js:11

I'm attempting to utilize the json file in the test component below, but I keep encountering the error: TypeError: Cannot read property 'map' of undefined. I have modified the file within the test.js component, and when testing it with a sa ...

Add and alter a script tag within the Vue template

I am currently working on integrating a payment service into my platform. The payment service has provided me with a form that includes a script tag. This question is a follow-up to a previous query on inserting a script tag inside a Vue template. Here i ...

Is there a way to verify an email address and transfer form data to a different HTML page for printing?

How do I troubleshoot email validity checking issues in my form? It works fine when no characters are entered, but fails when characters are inputted. What could be causing this problem? Additionally, I want to open a new HTML sub-file after form submissi ...

The AnchorEL component becomes unusable once a function has been executed for the first time

I am facing a challenge with anchorRef and struggling to understand how it works as I am new to React and have never used it before. After the onClickAway method is called, Material-UI shows an error stating that the anchorRef is set to null, but this warn ...

Trigger an action in the clean-up function of useEffect

I am facing an issue with a form component in a Material UI <Tab /> where users can update their address information. The data is fetched from the API using redux-thunk, and the form fields are pre-filled with server data before the update occurs. h ...

Symfony Form Validation through Ajax Request

Seeking a way to store form data with Symfony using an Ajax call to prevent browser refreshing. Additionally, I require the ability to retrieve and display field errors in response to the Ajax call without refreshing the page. I have a Symfony form setup ...

Challenges with basic e-commerce cart platform

Oh no, I'm in a bit of a mess. We've been utilizing a platform called Fat Free Cart (which has been pretty great so far) to construct our new online store. Now we're at the stage where we need to incorporate shipping options. As far as I ...

When a page loads, automatically refreshing a row in MySQL

I've been searching around, but haven't found a solution to my basic issue. I need help with creating a system where a user can only view a page once per day. Currently, clicking a button updates the MySQL Row, but users can bypass this restricti ...

Personalized search feature for Bootstrap tables

Below is the table structure: <table> <tr> <th>Number</th> <th>Name</th> </tr> <tr> <td>200.10.1234</td> <td>Maria Anders</td> </tr> <tr> < ...

Querying data from a label using jQuery

I am facing a challenge with reading label attributes in jQuery. I have multiple labels, each with the same class. These labels contain important information that I need to access. However, despite being able to select the object using $, I am struggling ...

How to transform multi-dimensional arrays to JSON format using JavaScript (and maybe jQuery)

Currently facing a Javascript dilemma where data storage is essential in the following format: MainArray(Array(JavaScript Object, JavaScript Object, etc etc..), Array(JavaScript Object, JavaScript Object, etc etc..), etc etc..) The main array consists of ...

The invocation of $.ajax does not work as a function

I'm encountering an issue when running npm start and trying to access the browser, I keep getting this error message in the stack trace. Error: $.ajax is not functioning properly at findLocation (G:\CodeBase\ExpressApp\routes\ind ...

A collection of items that mysteriously affix themselves to the top of the page as

Unique Context In my webpage, I have a specific div element with the CSS property of overflow: auto. Within this scrolling div, there is structured content like this: <h3>Group A</h3> <ul> <li>Item 1</li> <li>I ...

What is the impact of Javascript variable scope in the context of "for...in..." loops?

Imagine you have a code snippet like this: dict = {"key":"elem"} for (var elem in dict){ someFunction(function(){ anotherFunction(dict[elem]); }) } Question: Is elem still considered as the temporary variable created in the for...in... s ...

Exploring the different routing options for Nuxt.js: Dynamic versus Basic Routing

Can anyone suggest the best way to set up routing in Next.js for only Home, Gallery, and Contact us? Should I use dynamic routing or just keep it basic? Any ideas on how to path them? I'm still learning, so I would appreciate some guidance. I've ...

What is the most efficient way to substitute text within an HTML document?

Is there a way to switch between languages on a website to replace text on multiple pages with a simple button click? What is the most efficient method for achieving this? This code snippet only changes text in the first div. Is there a way to implement a ...

Ensure that when you click on the next dropdown menu opener button, the previous dropdown menu closes and only the new menu remains open

Take a look at this page first to get an understanding: On this page, I have implemented multiple dropdown menus that should open when clicked on their respective opener buttons (3 bar icon) and close either when clicked again or anywhere else on the page ...

The error of "No 'Access-Control-Allow-Origin' header is present on the requested resource" persists even after implementing the Access-Control-Allow-Origin header

I'm trying to retrieve JSON data from a Firebase cloud function. The JSON URL works fine on the browser and my Android app, but I encounter issues when trying to fetch it in my JavaScript code. This results in an error message: No 'Access-Cont ...

An issue with npm arises on Windows 10 insider preview build 14366

It appears that npm and nodejs are experiencing issues on the latest Windows version build 1433 When I ran the following command: npm -v events.js:141 throw er; // Unhandled 'error' event ^ Error: This socket is closed. ...