Jest Matcher issue: the value received must either be a promise or a function that returns a promise

As a dedicated practitioner of TDD, I am currently working on implementing an Exception in my code.

Below is the test code I have written:

  it.each([[{ id: '', token: '', skills: [''] }, 'Unknown resource']])(
    'should return an Exception when incorrect dto data',
    async (addSkillsDto: AddSkillsDto) => {
      await expect(() => {
        controller.addSkills(addSkillsDto)
      }).rejects.toThrow()
    }
  )

Next, here is the relevant code snippet:

  @Post('candidate/add-skills')
  async addSkills(
    @Body() skills: AddSkillsDto,
  ): Promise<StandardResponseObject<[]>> {
    const data = await this.candidateService.addSkills(skills)
    console.log(data, !data)
    if (!data) throw new HttpException('Unknown resource', HttpStatus.NOT_FOUND)
    else
      return {
        success: true,
        data,
        meta: null,
        message: ResponseMessage.SKILLS_ADDED,
      }
  }

When running Jest, the console output shows an error:

● Candidate Controller › should return an Exception when incorrect dto data

    expect(received).rejects.toThrow()

    Matcher error: received value must be a promise or a function returning a promise

    Received has type:  function
    Received has value: [Function anonymous]

      88 |       await expect(() => {
      89 |         controller.addSkills(addSkillsDto)
    > 90 |       }).rejects.toThrow()
         |                  ^
      91 |     }
      92 |   )
      93 |

      at Object.toThrow (../node_modules/expect/build/index.js:226:11)
      at candidate/candidate.controller.spec.ts:90:18

  console.log
    null true

      at CandidateController.addSkills (candidate/candidate.controller.ts:75:13)

Test Suites: 1 failed, 1 total

At this point, I am unsure of the necessary steps to make the test pass successfully.

Answer №1

Make sure to provide a Promise as an argument to the expect function. Currently, you are passing a function that does not return anything. Update

await expect(() => {
  controller.addSkills(addSkillsDto)
}).rejects.toThrow()

to

await expect(controller.addSkills(addSkillsDto)).rejects.toThrow()

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

The subcategory was not factored into my npm package

In my npm module 'ldap-pool', I'm facing an issue where the '@types/ldapjs' package, which is a dependency along with 'ldapjs', does not get installed when I add 'ldap-pool' to another project. This particular s ...

When an email link is clicked in Angular, Internet Explorer is automatically logged out and needs to be refreshed

I'm currently working on a project using an Angular 4 Application. One of the elements in my HTML code is an href link that has a mailto: email address. The issue I'm facing is that when I click on this link while using IE11, either I get autom ...

managing varying JSON responses for each request

Currently, I am utilizing json.net to deserialize JSON into C# objects. Although it generally works well, there are instances where instead of receiving an array, I receive an object. In my class (which was generated using http://json2csharp.com/ and the ...

Discovering the data type from its textual representation

Is it possible for TypeScript to automatically determine the generic argument of assertTypeof based on the value of expectedType? I am looking for a way to use the function below without having to specify number multiple times. playable example type Typ ...

What is the best way to set an array as the value for a state variable?

Looking at my function, I have the following situation: execute(e) { let { items } = this.context; let array: number[] = []; for (var i = 0; i < 2; i++) array = [...array, i]; this.setState( { items: array, } ) ...

Ways to implement the flow of change occurrences in the mat-select component

Seeking assistance with utilizing the optionSelectionChanges observable property within Angular Material's mat-select component. This property provides a combined stream of all child options' change events. I'm looking to retrieve the previ ...

Having trouble importing SVG as a React component in Next.js

I initially developed a project using create-react-app with Typescript, but later I was tasked with integrating next.js into it. Unfortunately, this caused some SVGs throughout the application to break. To resolve this issue, I implemented the following pa ...

Expanding the range of colors in the palette leads to the error message: "Object is possibly 'undefined'. TS2532"

I am currently exploring the possibility of adding new custom colors to material-ui palette (I am aware that version 4.1 will include this feature, but it is a bit far off in the future). As I am relatively new to typescript, I am finding it challenging t ...

Change icons in Ionic 5 when selecting a tab

How can I change my tab icons to outline when not selected and filled when selected? The Ionic 5 Tabs documentation mentions a getSelected() method, but lacks examples on its usage. I plan to utilize the ionTabsDidChange event to detect tab clicks, then ...

I'm puzzled as to why I am unable to invoke a class method within this callback function. The error message indicates a TypeError: 'this' is undefined

Currently, I am troubleshooting a challenge in my Angular application that involve TypeScript. The issue lies within a method in a TypeScript class: findArtistBidsAppliedByCurrentWall(bid):Observable<Bid[]> { console.log("findArtistBidsApplied ...

Tips for automatically assigning a default value in a material select within an Angular application

Currently, I have an Angular screen that displays data from a database using a Java REST API. There is a field called esValido which only contains values of 1 and 0 as shown in the initial image. https://i.sstatic.net/R4WCc.png My goal is to implement a ...

What is the best way to enhance the object type within a function parameter using TypeScript?

If I have a specified type like this: type Template = { a: string; b: string; c: string } I want to utilize it within a function, but with an additional parameter. How can I achieve this efficiently? When attempting to extend the type, TypeSc ...

Issue encountered while initializing a fresh project with Angular CLI version 13.1.0

I encountered an issue while trying to create a new project with Angular CLI v13.1.0 \ Installing packages (npm)...npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/ema ...

React's setState method is a key feature that allows

Can you explain the distinction between these two state updating functions and provide a recommendation on which one to use? I have tested both options in my application and they both seem to work properly. Approach 1 const [profile, setProfile] = useStat ...

Leveraging import and export functionality in TypeScript while utilizing RequireJS as a dependency

I am in the process of transitioning a complex JavaScript application from Backbone/Marionette to TypeScript. While making this shift, I want to explore the benefits of exporting and importing classes using files as modules. Is it necessary to incorporat ...

Angular 2: A guide to connecting Input with model property using getter and setter functions

I'm currently developing an Angular 2 web application. The model I have created consists of a few primary properties, along with other properties that are calculated based on those primary values. For each property in my model, I have implemented get ...

Issues may arise in TypeScript when you are working with an array of objects along with other properties within a type

I am encountering an issue with an object structure similar to the one below: let Obj = { ['0'] : { mode: 'x' }, getMode: () => 'x' } The problem arises when I attempt to create a type definition as shown here: type Obj = ...

Transform object properties into key-value objects using Typescript generics

When I receive a sorting object with a columnName and direction, I want to convert it into a key-value object for mongoose sorting. The return values are not matching up and I can't seem to figure out what I'm missing. These are the interfaces ...

When using a typescript subscription to collect data from an API, the information is stored in an array. However, only one piece of data can be

I have implemented a method to fetch data from an API using Angular: ngAfterViewInit() { this.exampleDatabase = new ExampleHttpDatabase(this._httpClient); var href = '/schuhe-store/status'; if (environment.production === false) { href ...

Managing Autocomplete Functionality in React with Material-UI, Both with and without a Pre

I am in need of an Autocomplete feature that offers the following functionalities: If the initial value has an id greater than 0, then I want the autocomplete to default to the provided object. If the initial value has an id less than or equal to 0, then ...