When attempting to trigger an error, the unit test will fail to pass

I am relatively new to Mocha, Chai, and Unit Testing. I'm currently attempting to create a basic test to verify the presence of Authorization headers in the request that passes through my middleware function. Despite trying various approaches such as using TypeError, throw(), error messages, and Error without success.... any assistance on this matter would be highly appreciated.

Middleware Function:

exports.verify = async (req, res, next) => {
      try {
        const headers = req.get('Authorization');
        let decodedToken;
    
        if (!headers) {
          const error = new Error('Not Authenticated');
          error.statusCode = 401;
          throw error;
        }
        const token = headers.split(' ')[1];
    
        try {
          decodedToken = jwt.verify(token, SECRET);
        } catch (err) {
          err.statusCode = 500;
          throw err;
        }
    
        if (!decodedToken) {
          const error = new Error('Not Authenticated');
          error.statusCode = 401;
          throw error;
        }
    
        req.userUid = decodedToken.userUid;
    
        const queryRef = await users.where('uid', '==', req.userUid).get();
    
        if (queryRef.empty) {
          const error = new Error('Not Authenticated');
          error.statusCode = 401;
          throw error;
        } 
        next();
      } catch (err) {
        log.error(err);
        next(err);
      }
    };

Test Script:

it('Should throw an error if no auth header provided.', function () {
  const req = {
    get: function () {
      return null;
    },
  };

  expect(function () {
    verify(req, {}, () => {});
  }).to.throw();
});

Just for reference - Error handling in app.ts:


app.use((err, req, res, next) => {
  const status = err.statusCode || 500;
  const message = err.message;
  const data = err.data || [];
  const userUid = req.userUid;
  const stack = err.stack;
  log.error(`STATUS: ${status} - MESSAGE: ${message} - STACK: ${stack}`);
  res.status(status).json(message);
});

Answer №1

Appreciate all the helpful advice from everyone. After doing some more research, I was able to solve this issue.

updated test as follows:

Test Case

it('Should trigger an error if no authentication header is provided.', function (done) {
  const req = {
    get: function () {
      return null;
    },
  };

  const callback = (err) => {
    if (err && err instanceof Error && err.message === 'Not Authenticated') {
      // test successful, called with an Error argument
      done();
    } else {
      // fail the test intentionally as the `err` does not match our expectations
      done(new Error('Assertion failed'));
    }
  };
  verify(req, {}, callback);
});

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

Sync issues observed with jQuery slide animations

I am currently utilizing a carousel slider that includes text content. When the user clicks on the 'next' button, the .carousel-text div slides up to hide the text, the carousel then moves to the next slide, and finally the .carousel-text on the ...

Is there a way to use a specific keyboard input to alter the characteristics of shapes on my webpage?

Is there a way to change certain attributes of a shape onscreen when a specific key is pressed by the user? For example, can I make it so that pressing "a" changes the color of the shape? I attempted to modify a mouse rollover event to work with the desir ...

Ways to collapse all rows that are expanded except the one that is currently open in iView Tables

Utilizing iView Tables to display data in a table with an expand option. As of now, when clicking on the expand button for a row, the row expands but previously expanded rows do not collapse, causing all expanded rows to be visible at once. Is there a wa ...

Run a JavaScript function once the one before it has finished executing

I need help with executing a series of JavaScript functions in a specific order, where each function must wait for the previous one to complete. I've tried multiple approaches but haven't been successful so far. Any suggestions would be greatly a ...

Improving the Roman Numeral Kata with JavaScript

As a newcomer to the world of coding, I have taken on the challenge of mastering the Roman Numeral Kata using Javascript. I am pleased to report that all the specifications are passing successfully. After refactoring the spec file, I am now focusing on re ...

I encountered an ERR_CONNECTION_REFUSED issue after deploying my Node.js application with Socket.io to Heroku

Upon running my live node.js Heroku app, I encountered the following error message in the web console: polling-xhr.js:264 GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=M2MDZUw net::ERR_CONNECTION_REFUSED Interestingly, when testin ...

How can I quickly duplicate the design of a JSON Object?

Perhaps the title is a bit basic. Essentially, I am looking for something similar to mysqldump ... --no-data .... For instance, I have a JSON object structured like this: { "key1" : "value1", "key2" : "value2", "key3" : { "key3a" : 1, "key ...

Chai property setEncoding is not valid for nock

When I used nock 9.1.6 to mock the Nylas API with chai 3.5.0, it worked flawlessly with the following code snippet: it('fails when no state is given and provider fails', () => { const user = fixture.elements.user1; const connector = new N ...

Issue encountered: Unable to add MongoDB object to database

Recently, I have encountered an issue with a script that looks like this: use first_db; advertisers = db.agencies.find( 'my query which returns things correctly ); close first_db; use second_db; db.advertisers.insert(advertisers); This error mess ...

The presence of MongoDB dot character in the key name

When working with MongoDB, I ran into an issue where keys with a dot (.) or dollar sign ($) are not allowed for insertion. However, while using the mongoimport tool to import a JSON file that contained a dot in it, surprisingly it worked without any proble ...

Associate a click event to a dropdown menu element to trigger on selection

My issue involves having multiple select elements. When one of them is changed, I am trying to bind a click event only to its next element with the .btn class. Below is the code snippet illustrating my problem: <div class="whole"> <ul> ...

What is the best way to set up a default item in my database for testing API CRUD operations using Jest?

I have an express API that is fully equipped to handle all CRUD operations specifically for Services. Utilizing a MYSQL database, my API interacts with a table named service. Currently, I am seeking a solution to insert a mock/default service object into t ...

Having an issue with my Django model not properly saving data when receiving a POST

Just dipping my toes into the world of ajax and Django, so please bear with me for my messy code. I'm facing an issue where my Django model is not saving the response even after receiving a POST request. I'm attempting to create a simple like/di ...

View complex response objects in Postman as easily digestible tables

I am interested in displaying the data provided below as a table using Postman Tests. The table should have columns for product, price, and quantity, with Items listed in rows. It's important to note that there may be multiple shippingGroups within th ...

To grab a specific CSS attribute from a stylesheet using JavaScript

I am looking for a way to extract the value from a CSS file using a JavaScript function. Take a look at my code snippet below: HTML file -> <link rel="stylesheet" type="text/css" href="test_css.css" /> <script type="text/javascript ...

Error: No targets with the name "taskname" were found for the custom Grunt task

Just recently, I decided to create my own custom task and here's the process: Started by making an empty folder named "custom-tasks" in the Document Root Next, I created the actual task file: "mytask.js" Implemented the functionality required for th ...

`Count the number of rows needed to accommodate text line breaks within a div element`

Is there a method to determine the number of lines that text breaks into using the CSS property word-break: break-all? For example, if I have a div like this: <div>Sample text to check how many lines the text is broken into</div> And the corr ...

Optimal approach to displaying views with Express.js and EJS

Recently, I came across a website that only renders EJS templates using Express.js routing. All the routes are defined in the /routes/index.js file. As the file grows with more routes being added, I am thinking about restructuring it to make it more develo ...

Should the request be sent to the parent or child component?

When a page is divided into various components, the data for each component is fetched asynchronously. Therefore, the parent component should trigger the request and pass it on to the child component, or alternatively, the request can be directly sent to ...

What is the best way to utilize an array that has been generated using a function?

After creating a customized function that generates an array of numbers, I encountered an issue where the array is not accessible outside the function itself. function customArrayGenerator (length, order){ // length = array length; order = integer order o ...