Ways to confirm an error message using Jest mock for throwing an error within a catch block

I'm having trouble mocking the catch block in jest for the code snippet

throw Error(JSON.stringify(studentErrorRes));
. While I can partially verify that an error is thrown, I'm unable to mock the error message properly. Typically, I use .mockRejectedValue to mock errors, but it's not working in this scenario. Can someone assist me on how to properly mock this?

During jest mocking, I can confirm that an error is thrown, but how can I verify the exact error message? If there are multiple keys within const studentErrorRes, how can I ensure that all keys have the expected values in my mock? I hope I'm not overcomplicating things.

import { SNSEvent } from 'aws-lambda';

export const studentAPIGetHandler = async (event: SNSEvent): Promise<any> => {
  try {
    const studentID = event.studentInfo.studentID;
    const studentPortal = StudentService.getStudentInfo(studentID);
  } catch (error) {
    const studentErrorRes = {
      apiName: SuudentAPIName.Student_Message,
      myMessage: 'Unable to get student API response',
    };
    logger.error(studentErrorRes.myMessage, error);
    throw Error(JSON.stringify(studentErrorRes));
  }
};

Part of test case for catch block


it("Catch block test for error", async () => {


    try {
        await studentAPIGetHandler(event);
    } catch(e) {
        expect(e).toThrowError; 
// this verifies that error is thrown , but not exact error message

    }

    });

Answer №1

Below is the solution for the unit test:

index.ts:

import { StudentService } from './student.service';

type SNSEvent = any;
const SuudentAPIName = { Student_Message: 'Student_Message' };
const logger = console;

export const studentAPIGetHandler = async (event: SNSEvent): Promise<any> => {
  try {
    const studentID = event.studentInfo.studentID;
    const studentPortal = StudentService.getStudentInfo(studentID);
  } catch (error) {
    const studentErrorRes = {
      apiName: SuudentAPIName.Student_Message,
      myMessage: 'Unable to get student API response',
    };
    logger.error(studentErrorRes.myMessage, error);
    throw Error(JSON.stringify(studentErrorRes));
  }
};

student.service.ts:

export class StudentService {
  public static getStudentInfo(id) {
    return {} as any;
  }
}

index.test.ts:

import { studentAPIGetHandler } from './';
import { StudentService } from './student.service';

describe('59871106', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should get student info', async () => {
    jest.spyOn(StudentService, 'getStudentInfo').mockReturnValueOnce({});
    const mEvent = { studentInfo: { studentID: 1 } };
    await studentAPIGetHandler(mEvent);
    expect(StudentService.getStudentInfo).toBeCalledWith(1);
  });

  it('should handle error', async () => {
    const mError = new Error('some error');
    jest.spyOn(StudentService, 'getStudentInfo').mockImplementationOnce(() => {
      throw mError;
    });
    jest.spyOn(console, 'error');
    const mEvent = { studentInfo: { studentID: 1 } };
    await expect(studentAPIGetHandler(mEvent)).rejects.toThrowError(
      JSON.stringify({ apiName: 'Student_Message', myMessage: 'Unable to get student API response' }),
    );
    expect(console.error).toBeCalledWith('Unable to get student API response', mError);
    expect(StudentService.getStudentInfo).toBeCalledWith(1);
  });
});

Results of unit test with coverage report:

 PASS  src/stackoverflow/59871106/index.test.ts (12.591s)
  59871106
    ✓ should get student info (10ms)
    ✓ should handle error (12ms)

  console.error node_modules/jest-mock/build/index.js:860
    Unable to get student API response Error: some error
        at /Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/59871106/index.test.ts:16:20
        at Generator.next (<anonymous>)
        at /Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/59871106/index.test.ts:8:71
        at new Promise (<anonymous>)
        at Object.<anonymous>.__awaiter (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/59871106/index.test.ts:4:12)
        at Object.it (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/59871106/index.test.ts:15:40)
        at Object.asyncJestTest (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:102:37)
        at resolve (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:43:12)
        at new Promise (<anonymous>)
        at mapper (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
        at promise.then (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:73:41)
        at process._tickCallback (internal/process/next_tick.js:68:7)

--------------------|----------|----------|----------|----------|-------------------|
File                |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
--------------------|----------|----------|----------|----------|-------------------|
All files           |    92.31 |      100 |    66.67 |    91.67 |                   |
 index.ts           |      100 |      100 |      100 |      100 |                   |
 student.service.ts |       50 |      100 |        0 |       50 |                 3 |
--------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        14.685s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59871106

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

Is it possible to evaluate the complexity of automating the user interface of a web application?

What are some common indicators of the challenges involved in automating the frontend of a web application? One example could be ensuring that all “critical” elements have stable ID attributes that do not change frequently. Are there any other similar ...

Mapping two arrays in JavaScript involves iterating through each element of the arrays

I'm having trouble displaying the content of two arrays contained within an object. When I map over RType.information.Type, I can display the content of the "Type" array. However, I am unable to display both Type[] and Price[]. I've tried various ...

switching the color of a path in an SVG when hovering over a

In the midst of working on SVG, I'm trying to implement a color change effect upon hover. The desired functionality is such that when hovering over the .business div, the color of the SVG business path should also change accordingly as specified in th ...

Is it necessary for Vue single file components (.vue files) to use `export default` or is it possible to use named exports instead?

export default may no longer be the recommended way to export modules, as discussed in these resources: After changing my Vue components from this: <script lang="ts"> 'use strict'; import {store} from '../../data/store' ...

Modifying the color of a non-active tab - Material UI Tabs

Is there a way to customize the color of inactive tabs in Material UI tabs? I have noticed that they currently appear black, as shown in the screenshot here: screenshot Thank you! ...

Arranging Functions in JavaScript

I am encountering an issue regarding the execution of JavaScript functions within HTML. Specifically, I am using dimple.js to create a graph and need to select an svg element once the graph is created via JavaScript. Despite placing my jQuery selector as t ...

Tips for validating an object with unspecified properties in RunTypes (lowercase object type in TypeScript)

Can someone please confirm if the following code is correct for validating an object: export const ExternalLinks = Record({}) I'm specifically asking in relation to the repository. ...

An unknown error has arisen: "The page https://registry.yarnpkg.com/react-native-template-react-native-template-typescript cannot be located."

Once I uninstalled the react-native-cli, I attempted to start a React Native project with a typescript template using the following command: npx react-native init MyApp --template react-native-template-typescript However, I encountered an error message: ...

Using Titanium for Android to Display High-Quality Images

My goal is to showcase a high-resolution image (minimum size of 2000x2000) on an Android device using Titanium, allowing users to scroll around it similar to a scroll view on iOS. However, I am aware that Android does not offer the same type of scroll view ...

Is the output returning before the AJAX call is completed?

Similar Question: How can I get the AJAX response text? When calling a JavaScript method that sends an Ajax request and receives a response in a callback function labeled "success," sometimes the JavaScript method returns a result as "undefined" inste ...

Cutting an image in ReactJS using the HTML5 canvas feature

Seeking a way to crop images in reactjs without relying on any external library. The goal is for users to upload an image and perform cropping using raw JavaScript, then replace the uploaded image. How can this be achieved without the use of libraries? Loo ...

When using PhpMailer to send emails, the response is not being returned to Javascript

Utilizing PhpMailer in a php/Javascript setup to send emails and while it is functional, it is not providing the expected success: function(response). Here is my javascript: <script type="text/javascript" language="javascript"> $ ...

What is the best way to select a color at random from an array without any duplicates?

When iterating through a group of 15 users to create a table row for each user, I am interested in randomly choosing a color from my theme's array of 4 colors for each user. How can I efficiently ensure that no two identical colors are next to each ot ...

Using JavaScript to utilize a variable containing a .match method with Regex Expression

Recently, I started delving into the world of regex with the aim of incorporating variables in my matches. Imagine I have a string that reads "Total: $168" My goal is to extract just the numerical value; 168. This is what I currently have: totalCost = t ...

Unable to retrieve the string contained within an element - JavaScript object literal

I am currently facing an issue where I am attempting to retrieve the text content of two div elements with classes .class-date and .class-time, but I keep encountering an Uncaught TypeError stating "e.siblings is not a function". I believe this may be a ...

Manipulating Typescript JSON: Appending child attributes and showcasing them alongside the parent item attributes

Here is a JSON data that needs to be processed: var oldArr = [{ "careerLevel": "Associate", "careerLevels": [ { "201609": 21, "201610": 22, "careerID": "10000120" }, { "201609": 31, "201610": 32, ...

Using TypeScript 4.1, React, and Material-UI, the className attribute does not support the CSSProperties type

Just starting out with Material-UI and we're utilizing the withStyles feature to style our components. Following the guidelines laid out here, I successfully created a classes object with the appropriate types. const classes = createStyles({ main ...

Encountering a problem while submitting the form - there appears to be an unexpected "s" token in the

This is my first attempt at creating a contact form using Node.js with Nodemailer. The goal is to have the form submitted through the website and sent directly to your inbox. Here is a snippet of my app.js file in the public folder: const form = document. ...

Angular 2 - Constructing dates in constructor - Error: Type 'Date' cannot be assigned to type 'string'

In my attempt to generate a fresh date object for an ngx-chart by referencing this specific example, I came across the following code snippet: constructor() { this.data = this.multi.map(group => { group.series = group.series.map(dataItem =& ...

Struggling to make PayPal Cordova Plugin function properly in both production and sandbox modes

While using the cordova paypal plugin and switching to sandbox mode, I encountered an error. The plugin can be found at https://github.com/paypal/PayPal-Cordova-Plugin https://i.stack.imgur.com/lD2EH.png Running the plugin in PayPalEnvironmentNoNetwork m ...