Attempting to verify a GraphQLError by utilizing expect().toThrow in my code test

I am facing an issue with a GraphQLError:

export const notFoundError = (msg: string): GraphQLError => {
    return new GraphQLError(msg, {
        extensions: { code: "NOT_FOUND" }
    });
};

Additionally, there is a function that throws this error

export function test() {
    throw notFoundError("no item found")
}

I am wondering how to properly test this in jest. Is this the correct approach?

expect(() => {
test();
}).toThrow((error: GraphQLError) => {
    // Expect statements here to verify message and code
})

Upon attempting this, I encountered the following error:

expect(received).toThrow(expected)

    Expected constructor name is an empty string
    Received constructor: GraphQLError

    Received message: "no item found"

          2 |
          3 | export const notFoundError = (msg: string): GraphQLError => {
        > 4 |     return new GraphQLError(msg, {
            |            ^
          5 |         extensions: { code: "NOT_FOUND" }
          6 |     });
          7 | };

If anyone has any advice on how to resolve this, please share!

Answer №1

Referring to the information provided in the documentation available at https://jestjs.io/docs/expect#tothrowerror

An example implementation could resemble the following:

test('testing notFoundError', () => {
  const notFoundError = (msg: string): GraphQLError => {
    throw new GraphQLError(msg, {
      extensions: { code: "NOT_FOUND" }
    });
  };

  expect(() => notFoundError("no item found")).toThrow(new GraphQLError("no item found", {
    extensions: { code: "NOT_FOUND" }
  }));

});

Please take note that it appears to specifically match the error message only.

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 feasible to invoke a method without any arguments on this basic subscription?

A BRIEF SUMMARY Implementing an observable in my code, I strive for maintaining cleanliness and efficiency by utilizing the detectChanges() method to update *ngIf= in the HTML. QUERY Is there a way to invoke the detectChanges() method within subscribe() ...

Is it possible to apply JavaScript object destructuring but make changes to certain values before assigning them to a new object?

After receiving movie data from an api, I am currently manually creating a new object with a subset of properties and modified values. Is there a more efficient way to achieve this using javascript/typescript object destructuring syntax? I specifically wa ...

Newest preact and typescript packages causing issues with type validation

Despite my efforts to integrate preact with TypeScript, I have encountered a problem where incorrect types can be passed without any error being raised. I am in the process of transitioning our codebase from plain JavaScript to preact with type scripting. ...

Checking a TypeScript project with various start points for linting

Within my extensive application that is constructed using webpack, there are numerous entry points that are generated dynamically. Each entry point requires specific target files to be created during the build process. I have already realized that when bu ...

The TypeScript compiler within WebStorm recognizes the TSConfig.json file as a valid TypeScript file

When working on my TypeScript project in WebStorm, I encountered an issue where the TypeScript compiler recognized my tsconfig.json file as a TS file. Adjusting TypeScript Settings in WebStorm: https://i.sstatic.net/EyX6T.png Error Encountered: https://i ...

Is there a way to configure tsconfig so that it can properly recognize ".graphql" files and aliases when they are imported into components?

Currently, I have encountered an issue where including "graphql" files in my components is leading to TypeScript errors due to unrecognized import pathing. Despite the error, the functionality works as expected. import QUERY_GET_CATS from "@gql/GetCats.gra ...

What is the best way to create an interface for an array of deconstructed objects within a mapping function?

After trying out different solutions, I find myself stuck with the same error message. Any advice or insights would be greatly appreciated. interface RequestedOptions { name: string; } interface TicketOptions { serviceId: string; description: ...

"Maximizing the Potential of refetchQueries in reason-apollo: A Comprehensive Guide

Encountering issues setting up refetchQueries with reason-apollo. Following a setup similar to the swapi example here, I have a listing and a form for adding new items via a mutation. Upon successful mutation, the goal is to refetch the items in the listin ...

Tips for effectively handling projects that call for varying versions of TypeScript within Visual Studio

In some cases, developers have had to downgrade their TypeScript version in order for it to work with a specific npm package version. Is it possible to do this with Visual Studio? I recently obtained a sample solution that utilized the angular2 npm packag ...

Cannot locate module using absolute paths in React Native with Typescript

I recently initiated a new project and am currently in the process of setting up an absolute path by referencing this informative article: https://medium.com/geekculture/making-life-easier-with-... Despite closely following the steps outlined, I'm en ...

Develop a visual representation of TypeScript class structures

My project involves a rendering engine similar to React, where I need to store classes instead of instances in an object for compiling purposes. For instance, let's say I have a component called Button that I want to dynamically instantiate. The proc ...

Adding to an existing array in SQLite by updating a column using Sequelize

My code includes a model definition for saving product data using Sequelize: This is how the Product model looks: import {Optional, Model, Sequelize, DataTypes } from 'sequelize'; /*This is the Product model used to save the data about products* ...

Updating reactive form fields with setValue or patchValue does not result in the fields being refreshed

This is a simplified version of my code snippet: ngOnInit() { //initialize form fields this.form = this.builder.group({ name: '', age: '', location: '', }); //Calling the service this. ...

The HTML5 datalist feature is only capable of displaying the first suggestion from the filtered array for autocomplete

I can't seem to display all the elements suggested in the datalist except for the first one. I've double-checked and confirmed that my array contains more than one element. It's puzzling why the other elements are not showing up in the sugge ...

Loop through a Map containing a List of objects in Angular 4

export class Individual { name: string, age: number, addressList: Map<string, Addresses[]>; } I am looking to extract and analyze all addresses of each individual. <div *ngFor="let person of individuals"> <div *ngFor="let addr o ...

Integrating one service into another allows for seamless access to the imported service's properties and methods within an Angular

After reviewing the content at https://angular.io/guide/dependency-injection-in-action, it appears that what I am trying to achieve should be feasible. However, I encounter this error when attempting to invoke a method on my injected service from another s ...

Angular 2: Firebase fails to provide a response

I am facing an issue with retrieving data from my Firebase using Angular 2 and TypeScript. While console.log() works, I am unable to return the value into a variable. My DataService looks like this: import {Injectable} from "angular2/core"; import ' ...

Why is it so difficult for the TypeScript compiler to recognize that my variables are not undefined?

Here is the code snippet in question: function test(a: number | undefined, b: number | undefined) { if (!a && !b) { console.log('Neither are present'); return; } if (!b && !!a) { console.log('b is not present, we ...

When using Angular9 with PrimeNG fullcalendar, it may encounter issues such as errors stating "Cannot find namespace 'FullCalendarVDom'." and "Please import the top-level fullcalendar lib"

Using primeng p-fullcalendar in my angular application. Encountering an error in the command-line: 'Cannot find namespace 'FullCalendarVDom' Also seeing this error in the browser: 'Please import the top-level fullcalendar lib before a ...

Establishing a typescript class as an interface

While attempting to upgrade to TypeScript 3.5, I ran into an issue with a signature that has been overlooked by the ts-compiler, despite being present for years. A third-party framework (knockoutJS) requires me to pass something that adheres to this: int ...