async function anticipate throw() sinon

One of my current challenges involves the following code snippet:

export class MyClass {

   public async get(name: string): Promise<string> {

     if(name == "test") throw new Error("name is eql 'test'");

    // do something
   }

}

I am trying to verify that the function 'get' is throwing as expected.

expect(myClass.get.bind(parser, "test")).to.throw("name is eql 'test'");

Unfortunately, this test does not seem to be working correctly. How can I go about fixing it?

Answer №1

In scenarios where only utilizing chai, assertions for errors thrown in asynchronous functions are not supported. One workaround is to employ try/catch along with async/await. Another option is to integrate the chai-as-promised plugin.

For instance:

index.ts:

export class MyClass {
  public async get(name: string): Promise<string> {
    if (name === 'test') {
      throw new Error("name is eql 'test'");
    }
    return '';
  }
}

index.test.ts:

import { MyClass } from './';
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);

describe('61342139', () => {
  it('should pass', async () => {
    const myClass = new MyClass();
    try {
      await myClass.get('test');
    } catch (error) {
      expect(error).to.be.instanceOf(Error);
      expect(error.message).to.be.equal("name is eql 'test'");
    }
  });

  it('should pass too', async () => {
    const myClass = new MyClass();
    await expect(myClass.get('test')).to.be.rejectedWith("name is eql 'test'");
  });
});

The unit test results along with a coverage report:

  61342139
    ✓ should pass
    ✓ should pass too


  2 passing (12ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |      75 |       50 |     100 |      75 |                   
 index.ts |      75 |       50 |     100 |      75 | 6                 
----------|---------|----------|---------|---------|-------------------

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

Angular 6: Sending Back HTTP Headers

I have been working on a small Angular Application for educational purposes, where I am utilizing a .net core WebApi to interact with data. One question that has come up involves the consistent use of headers in all Post and Put requests: const headers = ...

Executing multiple insert statements using the executeSql method

I am encountering an issue with multiple inserts in my code. Here is the snippet: db.openDatabase({ name: "data.db", location: "default" }).then(() => { db.executeSql( +"INSERT INTO check_item (name) VALUES ('Pneus - ...

Exploring ways to access elements within shadow-root (open) in Angular using SVG.js

I'm currently tackling a project involving Angular Elements. Within this specialized component, my goal is to incorporate SVG.js 3+. However, due to the necessity of utilizing ViewEncapsulation.ShadowDom in my component, I am encountering challenges w ...

What is the procedure for sending a secondary route parameter to the angular 2 services module?

I'm a beginner with Angular 2 and I'm seeking advice on how to pass multiple parameters to Angular's service module. For instance, here is the first parameter I'm passing to the service through the router link. In the home-component.ht ...

Rollup bundling with Typescript and troublesome rollup-plugin-typescript2 experience

I'm currently facing some unexpected challenges while attempting to extract a small portion of a monorepo into a web client library. The issue seems to be related to the configuration of Rollup, as shown below: import resolve from "rollup-plugin-node ...

JavaScript: exporting everything from ... causing excessive bloat in the build file

After building my react-app with create-react-app, I noticed a decline in performance. Here is the structure of my project: /store actions.ts reducers.ts /module1 module1.actions.ts module1.reducers.ts /moduleN moduleN.actions.ts m ...

Error: Unhandled promise rejection: Trying to access a property of null (specifically 'branch') causing a TypeError

While developing a dashboard for an Angular application, I encountered an error when trying to access the dashboard: ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of null (reading 'branch') TypeError: Cannot read propert ...

Passing a variable from a child component to a parent component in Angular 2 using EventEmitter and a

I am experiencing a challenge with the Event Emitter in my child component. My goal is to pass a variable with EventEmitter to the parent component, but I would like to include a timeout function. Currently, the code looks like this: CHILD: export class ...

Checking nested arrays recursively in Typescript

I'm facing difficulty in traversing through a nested array which may contain arrays of itself, representing a dynamic menu structure. Below is how the objects are structured: This is the Interface IMenuNode: Interface IMenuNode: export interface IM ...

Correct TypeScript function placement outside of return statement

I'm currently working on a NodeJS and Typescript project that already exists, and I've come across a function that seems a bit confusing to me. I don't think it's well-written either. This particular function is responsible for compari ...

The 'log' property cannot be found on the type '{ new (): Console; prototype: Console; }' - error code TS2339

class welcome { constructor(public msg: string){} } var greeting = new welcome('hello Vishal'); Console.log(greeting.msg); I encountered an error at the Console.log statement. The details of the error can be seen in the image attached below. ...

Testing the functionality of an event that is not linked to an event emitter

Below is the code snippet I'm working with: private client: any; this.client = mqtt.connect(url, mqttOptions); this.client.on('message', (topic: string, message: string) => { console.log('came inside onMessage'); ...

Deployment of a NextJS14 app to Vercel encountered an issue: Unexpected token '<' found in JSON at position 0

Here is the issue at hand: next: 14.1.4 next-auth: 4.24.7 node version: 20 This is the structure of my authentication folder: No errors occur when running npm run dev I've been investigating this issue for three days, but I am still stuck. I belie ...

Compiling TypeScript to JavaScript with Deno

Currently experimenting with Deno projects and looking for a way to transpile TypeScript into JavaScript to execute in the browser (given that TS is not supported directly). In my previous experience with NodeJS, I relied on installing the tsc compiler via ...

Using Cypress.Promise in a Cypress command causes type conflicts

When using Cypress 8.x.x, the following Cypress command works fine: declare global { namespace Cypress { interface Chainable<Subject> { login(): Chainable<Token>; } } } Cypress.Commands.add('login', () => { ret ...

Omit select dormant modules when building (Angular5)

Currently, I am collaborating on a project that is being implemented across various customer instances. Within the project, we have several lazy loaded modules, with most of them being utilized by all customers. However, there are certain modules that are ...

Unable to detect tsc after installing globally within Windows Sandbox

I followed the instructions provided here to install TypeScript globally. npm install -g typescript After installing both inside vscode and outside, I encountered an issue where tsc --version does not work and shows 'tsc is not recognized'. Int ...

utilizing regular expressions in TypeScript

I'm currently working with Angular 2 and I have a URL link: www.abcd.com/Computers_Accessories/panache-air-pc/P-coac-20620024815-cat-z.html#newId=P-coac-41130779424?trackId=paym&subTrackId=&infitag=1234 My goal is to remove the portion #newId ...

Navigating an object in Typescript

I attempted to find some instructional materials, but unfortunately, they did not offer much useful information. Here is the JSX setup I am working with: Object: export const Project1 = [ { name: 'Interior Design Website', d ...

Modifying the property value based on the selected item from a dropdown menu in Angular 2

I am brand new to Angular 2 and I have come across the following code snippet. <select name="shape_id" (change)="changeShape()"> <option *ngFor="let shape of shapes" [ngValue]="shape.name"> {{shape.name}} </option> </s ...