What steps are involved in testing an ErrorHandler in express.js?

I am attempting to run a fail case test for this TypeScript function using Sinon, however, I am unsure how to proceed. Can anyone provide assistance?

 public async findById(id: number): Promise<UserModel> {
    const user = await this._userModel.findByPk(id);
    if (!user) throw new NotFound('User not found');
    return user;
  }

Answer №1

Successfully solved the problem and successfully developed a unit and integration test:

Integration Test:

it('should fail to find user by id', async function () {
   Sinon.stub(Model, 'findByPk').resolves(null);
   const response = await chai.request(app).get('/users/999').send({
     params: 999,
   });

   expect(response.status).to.equal(404);
});

Unit Test:

it('should fail to find user by id', async function () {
  sinon.stub(Model, 'findByPk').resolves(null);

  try {
    await userService.findById(999);
  } catch (e) {
    const error = e as Error;
    expect(error).to.be.instanceOf(NotFound);
    expect(error.message).to.equal('User not found');
  }
});

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

Gmail does not seem to be receiving the emails sent through Nodemailer Ethereal

I have been attempting to send emails using the following function on an express js server. While it appears to be functioning correctly, the emails I send do not appear in my Gmail inbox or spam folder. The function I am using is: const transporter = nod ...

Why does my partial file keep eluding me?

Currently, I am facing issues setting up my nodejs app. I am using Webstorm's project creator to select a nodejs express app with handlebars as the engine. Additionally, I have included express-handlebars in my setup. However, when I try to include a ...

Spotlight a newly generated element produced by the*ngFor directive within Angular 2

In my application, I have a collection of words that are displayed or hidden using *ngFor based on their 'hidden' property. You can view the example on Plunker. The issue arises when the word list becomes extensive, making it challenging to ide ...

What is the recommended frequency for regenerating the jti claim?

In the development of my REST API, I am incorporating a JWT based authentication system with intentions to utilize the JWT_ID claim within the token. As outlined by Auth0, the JWT ID attribute allows for a token to be utilized only once: jti (JWT ID): Un ...

Angular version 6 allows for specifying input types as numbers and displaying two decimal digits after the comma

How can I format user input to display as currency with thousand separators in Angular? <input type="number" (ngModelChange)="calculateSum()" (change)="calculateAmount(invoiceQuota)" [ngModel]="invoiceQuota.controls.grossAmount.value"> I have attem ...

Exploring Angular 4.3 Interceptors: A Practical Guide

I am currently working on a new app that needs authorization headers. Normally, I follow a similar approach to what is described in this article on scotch.io. However, I have recently learned that Angular 4 now fully supports HTTP Interceptors through the ...

The letter 'X' is not suitable for use as a JSX component because its return type 'Element[]' does not qualify as a valid JSX element

Currently, I am working on rendering two simple joke cards in TypeScript. The cards are displaying correctly in my browser, but I've encountered an error message that says: 'Jokes' cannot be used as a JSX component. Its return type 'Ele ...

Attention: WARNING regarding the NEXTAUTH_URL in the Development Console

While working on my Next.js web application with next-auth for authentication, I came across a warning message in the development console. The message is related to reloading the environment from the .env.local file and compiling certain modules within the ...

What improvements can be made in the MongoDB structure for a more efficient package or wallet system?

I am currently developing a package/wallet system that involves multiple users. Within my mongodb database, I have organized the data into 4 collections: Business const businessSchema = new mongoose.Schema({ name: { type: String, unique: true }, . ...

What is the best method for configuring a proxy while utilizing axios for sending requests?

I've been utilizing a package called 'concurrently' to simultaneously run my client and server on localhost. The client is running on port 3000, while the server operates on port 5000. I configured the proxy in the server's package.json ...

Unable to fake a fetch request using the 'fetch-mock-jest 1.5.1' library

I am attempting to simulate a fetch call using thefetch-mock-jest library, but the code continues to try accessing the remote address and ultimately fails with the error message FetchError: request to https://some.domain.io/app-config.yaml failed, reason: ...

Cross-Origin Resource Sharing (CORS) issue: The Same Origin Policy prevents accessing the external content from http://api.com. (Cause: Failed CORS request). Error code: (null)

An error occurred due to the Cross-Origin Request being Blocked by the Same Origin Policy. The remote resource at http://bayut-api-v1:4000/properties/list?purpose=for-sale&locationExternalIDs=5002&sort=city-level-score&location=dubai&page=1 ...

Submitting an HTTP POST REQUEST with both an image and text

Is there a way to send an image with text from VueJs to an ExpressJs backend? I've currently implemented two HTTP POST requests for this process. Please note: "this.albumName" and "this.albumDesc" contain text, while the formData variable holds the ...

Understanding the mechanisms of Promise functionality within Typescript can be challenging, particularly when encountering error messages such as "type void is not

Recently, I've delved into the world of Typescript. Despite my efforts to stay true to the typing system, I've encountered a challenge that forces me to resort to using the any type: The issue arises with a function that returns a promise: sav ...

Leverage the generic types of an extended interface to simplify the creation of a shorthand type

Attempting to streamline my action shorthand that interacts with AsyncActionCreators. A function has been crafted to accept a React dispatch: Dispatch<T> parameter: const fetchProfileAction = actionCreator.async<void, Profile, any>('FETC ...

Obtaining specific information about the target item that a source item was dropped on (using ng2-dragula in Angular)

Issue: I need assistance in implementing the following functionality using the ng2-dragula drag behavior. I am working on creating a feature similar to the app-launcher found on iOS and Android devices. I aim to drag an item A and drop it onto anothe ...

An ambient module will not be successfully resolved through a relative import operation

As per the typescript documentation (https://www.typescriptlang.org/docs/handbook/module-resolution.html): A relative import is resolved in relation to the importing file and does not resolve to an ambient module declaration. However, it also states: ...

Learn the process of uploading files using the multer library in a nodejs application

I'm facing an issue while trying to upload a file using multer. The file is not getting uploaded and I would appreciate any insights into what might be causing this problem in the code. According to the multer documentation, req.body should carry the ...

Can Express JS be utilized with an MS Access database?

Can a Microsoft Access database (.accdb) be utilized as the back-end for an express js application? I have attempted various packages for connecting it without success. Are there alternative methods to connect an MS Access db with an express REST API? ...

Understanding how to retrieve the value count by comparing strings in JavaScript

In my array object, I am comparing each string and incrementing the value if one letter does not match. If three characters match with the string, then I increase the count value; otherwise, it remains 0. var obj = ["race", "sack", &qu ...