The failure of a unit test involving Jest and try-catch

I am facing an issue with creating unit tests using jest.

exportMyData.js

const createJobTrasferSetArray = async () => {
  const data = exportData();
  const jobTransferSet = [];

  try {
    data.forEach((element) => {
      const JobPathArray = element.JobPath.split(/[,\r\n]+/)
        .filter((JobPathElement) => JobPathElement !== '');

      // Create an object
      const jobTransferSetObj = {
        coworkerID: element.CoworkerID,
        jobPath: JobPathArray,
      };
      jobTransferSet.push(jobTransferSetObj);
    });
    return jobTransferSet;
  } catch (e) {
   console.error(`Couldn't create jobTransferSet Array: ${JSON.stringify(e)}`);
return e;
  }
};

exportMyData.test.js

const exportData = require('./exportMyData');

describe('Read data from Excel and create formatted JSON output', () => {
//Test passed through
  it('convert read data from Excel to an array', async () => {
    mockedJobTransferSetRaw.mockReturnValue(jobTrasfarSetRaw);
    const result = await exportData.createJobTrasferSetArray();
    expect(result[0].coworkerID).toEqual(jobTransferSetArray[0].coworkerID);
    expect(result[0].jobPath).toEqual(jobTransferSetArray[0].jobPath);
    expect(result).not.toBeNull();
  });
  //Test fails
  it('Error on convert to an array', async () => {
    try {
    const result = await exportData.createJobTrasferSetArray();
    result.mockRejectedValue(new Error('something went wrong'));
    } catch (error) {
      expect(error.message).toEqual('Error: something went wrong');
    }
  });
});

I believe there is an error in my test case, but I am struggling to find the solution. Any help would be greatly appreciated!

Answer №1

It's generally recommended to avoid using try/catch blocks within unit tests whenever possible. Instead, you can utilize jest's built-in helpers for handling asynchronous code:

    await expect(class.method(param)).rejects.toThrow();
    await expect(async () => class.method(param1, param2)).rejects.toThrow(Exception);

Additionally, in your current implementation, the try block is empty, which means it won't catch any errors. It's important to have some logic or method calls inside the try block for it to be effective:

    try {
    // Call some methods, perform actions...
    } catch (error) {
      expect(error.message).toEqual('Error: something went wrong');
    }

If possible, try to refactor your code so that the try/catch block is not necessary. Start by addressing the issue of the empty try/catch block.

Based on my understanding, it appears that you are calling a method that may throw an exception. You might consider mocking the return value of this method after invoking it:

    const result = await exportData.createJobTransferSetArray();
    result.mockRejectedValue(new Error('something went wrong'));

It's unclear what your original intention was with that section of code. If you provide more details about its purpose or underlying logic, we can offer better 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

A guide on organizing and categorizing data by name with angularjs

Presented here is a list of descriptions associated with specific names. I am seeking guidance on how to group or list the descriptions by name. html: <body ng-app="app" ng-controller="MainCtrl"> <div ng-repeat="nameGroup in loopData"> & ...

Tips for Sending Request Parameters to Angular Application

My Angular app, created with Angular CLI, is hosted on Heroku using express. The setup looks like this: const express = require('express'); const app = express(); // Serve the static files in the dist directory app.use(express.static(__dirname + ...

What is causing the default switch to constantly loop in repetition?

Currently, I am working on a Discord bot using discord.js and utilizing a switch statement. However, I am encountering an issue where the "default:" case keeps repeating itself every time any other case is executed. I have already investigated for cases w ...

Are you familiar with manipulating the JSON data array retrieved from an Ajax response?

Is it possible to handle a response from AJAX request in PHP? I'm not very familiar with JavaScript, so I'm struggling with this one. This is what I have managed to put together: var base_url = 'http://dev.local/westview/public'; $(& ...

Generate a dynamic jqplot chart using data retrieved from a variable and JSON data

I'm struggling with loading data into a jqplot chart via variables as it only displays the first value. I am puzzled as to why this is happening. JavaScript: $(document).ready(function () { var sin = [[20, 10, 0, 10, 15, 25, 35, 50, 48, ...

Encountering a Node Js post handling error with the message "Cannot GET /url

This is my ejs file titled Post_handling.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>POST-Handling Page</title> </head> <body& ...

Is it possible to load Javascript using AJAX with jQuery?

So I have this JavaScript code that I insert into a webpage using the following: <script type="text/javascript" src="http://ext.nicovideo.jp/thumb_watch/sm13154955?w=640&h=395"></script> It basically places an object/embed code into the w ...

Tips for executing embedded scripts within templates

I am using a controller to display the Instagram embedded code <div class="instagram_here" [innerHtml]="instagram_embeded_code"></div> However, it is only showing a blank Instagram block. https://i.stack.imgur.com/gNPDL.png I suspect there m ...

Modifying td background color according to values in a PHP array

Trying to update the background color of a td element with the code below. However, it seems that the code needs some adjustment as the color is not being applied. Any assistance or alternative solutions would be greatly appreciated. Snippet of PHP code: ...

Retrieving entities from a text

I found a script on the Webdriver.io website that looks like this (adjusted for testing) const { remote } = require('webdriverio'); var assert = require('assert'); ;(async () => { const browser = await multiremote({ ...

Error: The function $.simpleTicker is not defined

Every time I try to call a jQuery function, an error shows up: Uncaught TypeError: $.simpleTicker is not a function I attempted changing $ to jQuery but it didn't resolve the issue. This represents my jQuery code: (function ($) { 'use ...

updating the row of an html table with elements from a javascript object

I am faced with the task of dynamically adding rows to a table based on the number of elements in my JavaScript object. The object consists of keys and arrays of values. userobject={ ID: [1,2,3] IP_Address: ["12.21.12 ...

Difficulty recognizing sessions in production for a self-hosted Next.js application using Clerk Dev Auth

Having trouble finding the next step in debugging as I couldn't resolve the issue on Clerk's Discord or GH Issues. It seems like it might be a Next.js problem rather than a Clerk one? I am currently running a self-hosted next.js app in a docker ...

Make an axios request multiple times equal to the number of items in the previous response

In my project, I am using the axios library to convert addresses into their respective coordinates. First, I fetch a list of addresses from an API. Next, I take the RESPONSE object and use Google API to convert each address to coordinates. Finally, I wan ...

The error code 405 (Method Not Allowed) occurs in Ajax when the action field is empty or identical to the current page

Special thanks to @abc123 for sharing the code below in one of their posts: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <form id="formoid" a ...

What is preventing the click function on a dynamically created button from being executed in jQuery?

Take a look at this jsFiddle where I illustrate my issue. Whenever I click on the "Add an ingredient" button, the button click event is triggered. My issue arises when I click on the "Create a subtitle" button because it dynamically creates "Add an ingredi ...

What is the best way to calculate the variance between the most recent and previous data points in an array in the span of an hour using JavaScript

Here is an array of objects I am working with: 0: {time: '2021-12-02T23:53:54.062Z', value: 558316} 1: {time: '2021-12-03T00:53:53.959Z', value: 558452} 2: {time: '2021-12-03T01:53:53.934Z', value: 558588} 3: {time: '2021 ...

The added class is not being successfully applied to the ClassList

I'm currently working on a page where I want the colors of a button and the background to switch when the button is clicked. document.querySelector("body.light").classList.toggle("dark"); document.querySelector("button.dark").classList.toggle("light" ...

Postman's ability to capture elements that meet specific criteria set by another element

Here is the output of my response code: [ { "id": 364, "siteName": "FX21 - PortA", }, { "id": 364, "siteName": "FX21 - PortB", }, { "id": 370, "siteName": "FX05 - ER", }, I'm tr ...

creating a loop to handle AJAX requests for JSON data

My JSON call successfully loads the data.root.offer[0].region data into a div with the class .region. Here is the code snippet: $.getJSON('json/data.json', function(data) { $('.region').html('<p>' + data.root.offer[0] ...