Ways to evaluate a String that is thrown using Jest

I encountered a scenario where a function throws a string.

Although Jest provides the toThrow matcher for testing functions that throw errors, it only works when an Error object is thrown.

Is there a way to test if a string is thrown using Jest?

The given code snippet:

async function funToTest(): Promise<number> {
  if (Math.random()) throw 'ERROR_CODE_X';
  return 10;
}

describe('funToTest', () => {
  it('should throw `ERROR_CODE_X`', () => {
    await expect(() => funToTest()).rejects.toThrow('ERROR_CODE_X');
  });
});

produces the following result:

funToTest › should throw `ERROR_CODE_X`

    expect(received).rejects.toThrow(expected)

    Expected substring: "ERROR_CODE_X"

    Received function did not throw

This clearly indicates that the function did not throw as expected, even though it does indeed throw.

If the string throwing part is changed to an Error (throw new Error('ERROR_CODE_X')), then the test passes successfully.

Answer №1

When testing with .reject, make sure to expect the rejected value in order to use standard expect matches.

async function funToTest(): Promise<number> {
  throw "ERROR_CODE_X";
}
async function funToError(): Promise<number> {
  throw new Error("ERROR_CODE_X");
}

describe("funToTest", () => {
  it("should throw `ERROR_CODE_X`", async () => {
    await expect(() => funToTest()).rejects.toMatchSnapshot();
    await expect(() => funToTest()).rejects.toEqual("ERROR_CODE_X");
  });
  it("should not throw `ERROR_CODE_X`", async () => {
    await expect(() => funToError()).rejects.toThrowErrorMatchingSnapshot();
    await expect(() => funToError()).rejects.toEqual("ERROR_CODE_X");
  });
});

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

Tips for successfully interacting with dynamic text areas using Protractor:

My current project involves e2e testing for an Angular 4 application with Protractor. Despite my efforts, I am struggling to locate a unique id, class, name or text identifier for a specific textarea within the application code. I need assistance in find ...

Error in StoryBook addon-docs: "No props discovered for this particular component" when utilizing TypeScript

Encountering an issue with a TypeScript and StoryBook project: The table displaying component properties is not generated nor visible in the StoryBook "Docs" tab on a TypeScript-based project setup. Instead of the expected table, a message saying "No pro ...

Learn how to utilize the "is" status in Postma within your code, even when this particular status is not included in the response

Service.ts Upon invoking this function, I receive a JSON response similar to the following: public signupuser(user: Users): Observable<boolean> { let headers = new Headers(); headers.append('Content-Type', 'application/json&a ...

Vetur is experiencing issues with template functionality, such as not properly checking data and methods

I have incorporated the vetur extension into my Visual Studio Code for a Vue project using TypeScript. I recently discovered that vetur has the capability to perform type checks within the template tag for props, methods, and even variables. However, in ...

Using React with Typescript and ie18next to fetch translations from an external API

In the past, I have experience working with i18next to load translations from static json files. However, for my current project, I need to load all translations from an API. How can I achieve this? Additionally, how can I implement changing the translat ...

What is the process for creating a nullable column in TypeORM?

Within my User entity, there is an optional column for the user's avatar image: @Entity() export class User { @PrimaryGeneratedColumn('uuid') id: string @Column({ unique: true }) email: string @Column({ unique: true }) ...

Exclude a file in Typescript, regardless of its import status

When attempting to exclude a *.ts file from compilation by adding it to the "exclude" property in tsconfig.json, I am facing an issue. If I import that excluded file somewhere in the code, TypeScript ignores the exclusion and compiles it anyway. How can I ...

Check the functionality of a React functional component by conducting unit tests on its functions

Is there a way to properly unit test a function within a Functional component in React? Since wrapper.instance() will return null for functional components, what is the best approach to ensure this function is included in testing to achieve maximum coverag ...

Modifying Data with MomentJS when Saving to Different Variable

After attempting to assign a moment to a new variable, I noticed that the value changes on its own without any modification from my end. Despite various attempts such as forcing the use of UTC and adjusting timezones, the value continues to change unexpec ...

The NX monorepo from @nrwl is unable to locate the .svgr configuration file within the lib directory

Recently, I started working with NX Monorepo that consists of 2 separate react applications. In order to share icons between these apps, I decided to create an icons library. I made changes to the project.json file of the icons library and added a svg com ...

Beautiful parentheses for Typescript constructors

I'm working on a project where I've installed prettier. However, I've noticed that it always reformats the code snippet below: constructor(public url: string) { } It changes it to: constructor(public url: string) {} Is there any way to sto ...

Customizing dropzone color while dragging an image in Angular

I have been using Angular and created an image input field. Within this input field, I implemented a dropzone that allows users to drag files into it. Is there a way for me to modify the background of the dropzone when a file is being dragged into it? Thi ...

I am looking to enhance my array of objects by implementing a filter. It is important that the filter does not allow for duplicate checkboxes with the

My website : On the left-hand side of my webpage, there is a set of checkboxes with some repeated names that I don't want. For example, "Rice" is repeated twice but I only want it to display once. When checking the Rice checkbox, it should show all c ...

Avoid connecting redux to a component in TypeScript and React

I am having an issue with the "connect" function not wrapping my App component, causing Redux to not work. I have tried cloning some repositories with react+redux+typescript and they all work fine, but my application does not. As a result, I am unable to ...

Identifying the End of an HTML Video in Angular 2

Seeking assistance with detecting the end of an HTML video in Ionic2 (Angular2 and Typescript). The relevant code snippets can be found below: Template: <video poster="" id="v" playsinline autoplay webkit-playsinline onended="vidEnded()"> <s ...

The functionality to generate personalized worldwide timezone pipe is not functioning

I'm completely new to Angular and I've been working on creating a custom pipe for adjusting timezones. The idea is to allow users to select their preferred timezone and have the offset applied accordingly. To start, I created a file called timez ...

What is the proper way to specify the type of a mixed Map?

private readonly _subscriptions:???? = new Map([ ['a', new Map()], ['b', new Map()], ['c', new Map()], ['d', []] ]) No suitable type was found for this map. I tried vario ...

When the *ngFor directive disrupts the CSS Grid Layout, resulting in all items being displayed in a single column

I am a beginner in the world of programming and web development. Currently, I am working on building my own personal website. My goal is to arrange boxes in a grid with 4 columns, similar to the layout you can find at this link: Each box represents an ob ...

The Mui datepicker displays the day and month in reverse order

Do you have trouble with date search filter using the mui datepicker component? It seems that when entering a date in the input and clicking on search, the day gets swapped with the month. For instance, if you input 03/05/2022, it returns Sat Mar 05 2022 ...

The command "tsc" was not found in this bash session

Currently, I am using a MAC and attempting to set up TypeScript. I followed the installation process by running sudo npm install -g typescript and received the following output: Password: /Users/<myuserid>/node/bin/tsc -> /Users/<myuserid& ...