Is there a way to successfully capture the mongodb error for jest testing purposes?

In order to create a user schema using mongoose, I have the following code:

/src/server/models/User.ts:

import { model, Schema } from "mongoose";

export const UserSchema = new Schema({
  address: {
    type: String,
  },
  email: {
    required: true,
    type: String,
    unique: true,
  },
  name: {
    required: true,
    type: String,
    unique: true,
  },
});

const User = model("User", UserSchema);

export default User;

To test the insertion of a user object without including the name field and return an error from mongodb, I wrote the following code:

/src/tests/db.spec.ts:

import { MongoMemoryServer } from "mongodb-memory-server";
import mongoose, { Model } from "mongoose";
import { UserSchema } from "../server/models/User";

let mongoServer: MongoMemoryServer;
const opts = {
  useCreateIndex: true,
  useNewUrlParser: true,
  useUnifiedTopology: true,
};

describe("Users", () => {
  let User: Model<any>;
  beforeAll(async () => {
    mongoServer = new MongoMemoryServer();
    const mongoUri = await mongoServer.getConnectionString();
    const db = await mongoose.connect(mongoUri, opts);
    User = db.model("User", UserSchema);
  });

  afterAll(async () => {
    await mongoose.disconnect();
    await mongoServer.stop();
  });

  describe("User Creation", () => {
    it("Should return an error if 'name' is missing", async () => {
      const newUser = new User({
        address: "address",
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a7f796f784a6d676b63">[email protected]</a>",
      });
      const createdUser = await User.create(newUser);
      expect(createdUser).toThrowError("User validation failed");
    });
  });
});

The test failed with this error message:

● Users › User Creation › Should return an error if 'name' is missing

    ValidationError: User validation failed: name: Path `name` is required.

      at new ValidationError (node_modules/mongoose/lib/error/validation.js:31:11)
      at model.Object.<anonymous>.Document.invalidate (node_modules/mongoose/lib/document.js:2413:32)
      at p.doValidate.skipSchemaValidators (node_modules/mongoose/lib/document.js:2262:17)
      at node_modules/mongoose/lib/schematype.js:1058:9

How can I resolve this issue?

Answer №1

As stated on the Jest documentation about rejects, I successfully applied the rejects method in my test:

it("Ensuring an error is returned when name field is absent", async () => {
      const newUser = new User({
        address: "anAddress",
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c292f392e1c3b313d3530723f3331">[email protected]</a>",
      });
       await expect(User.create(newUser)).rejects.toThrow("Path `name` is required")
    });

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

Unable to place value into an array following the invocation of a function in Angular 9

Within an array I established, I am encountering an undefined value when I use console.log. Take a look at my component.ts below: export class OrderExceptionReportComponent implements OnInit { public sessionData: ExceptionReportSessionData[] = []; n ...

Emphasize the search term "angular 2"

A messenger showcases the search results according to the input provided by the user. The objective is to emphasize the searched term while displaying the outcome. The code snippets below illustrate the HTML and component utilized for this purpose. Compon ...

The unpredictability of MongoDB Atlas function performance when called via HTTPS versus when run in debug mode

An error occurs when attempting to make a https request using Postman, even though the function runs successfully in the debugger. This issue is best demonstrated with screenshots The function runs smoothly in the MongoDB function editor: working functio ...

Using Class as a Parameter

I recently started using TypeScript and encountered an implementation issue. I'm working on a class that takes another class as an argument. The challenge is that it can be any class, but I want to define certain possible class properties or methods. ...

Exploring the concept of inheritance and nested views within AngularJS

I've encountered a challenge while setting up nested views in AngularJS. Utilizing the ui-router library has been beneficial, but I'm facing issues with separate controllers for each view without proper inheritance between them. This results in h ...

The error message states that the property 'id' is not found on the 'User' type when using Passport and Typescript

When I try to access req.user.id while using PassportJS in Express with Typescript, I encounter the following error: Property 'id' does not exist on type 'User'.ts(2339) Upon logging req.user to the console, the id property is clearly ...

Running a JavaScript file from Docker to fill a MongoDB database is not working when using the WSL shell on Windows 10

I'm facing some issues while trying to populate my MongoDB using a script. Every time I run the script, I encounter errors even though the Docker container is up and running. For reference, I'm on Windows 10 using WSL shell. https://i.stack.img ...

What is the best way to retrieve an object when a value is not found? Consider implementing a looping mechanism with a specific condition in React and TypeScript to successfully

Greetings, I am faced with an array of objects structured as follows: const arr_obj = [ { id: '1', jobs: [ { completed: false, id: '11', run: { ...

Unable to access component properties through react-redux

Context: A React Native application utilizing Redux for managing complexity. Versions: typescript v3.0.3 react-native v0.56.0 redux v4.0.0 @types/react-redux v6.0.9 @types/redux v3.6.0 Issue: The main JSX component in my app is unable to access proper ...

There seems to be an issue with the server: Xt1.deprecate function is not defined

Currently, I am utilizing next.js version 13.4.12 with next-auth version 4.22.3 and prisma version 5.0.0, while also incorporating @next-auth/prisma-adapter version 1.0.7 in a TypeScript setup. Additionally, I have diligently followed all the necessary bo ...

Received an error notification when attempting to execute the command "mongo --port 27003"

Encountering the error errno:61 Connection refused when trying to run mongo --port 27003 in Mac OSX terminal However, running just mongo works without any issues. ...

TypeScript allows for the declaration of a function that includes a mandatory property within the function signature

If I desire a tagged function with an interface such as: interface TaggedFun { (args): void; tag: boolean; } It appears that declaring a function to match this signature is not possible (since any function literal will lack the mandatory tag prop ...

Clearly define in typescript that a variable should not be null

Encountering an issue with typescript involving a mongoose model that is interface casted. import { Schema, model } from "mongoose"; interface IUser { userId: string guildId: string cash: number bank: number } const userSchema = ...

What is the best way to ensure a model property is unique when using loopback 4 with mongoDB?

I am currently facing a challenge in making the name field unique within loopback 4 models that are connected to a MongoDB datasource. Despite my attempts to use index: { unique: true }, I have not been successful. I have also looked into the documentati ...

Exploring TypeScript reflections within a specific namespace

(Building upon previous discussions about dynamically loading a TypeScript class) If I am currently within a namespace, is there a method to reference classes within the namespace in order to utilize 'reflection' to invoke their constructors? n ...

Getting into particular fields of an embedded object array using a dynamic variable in Meteor: a step-by-step guide

Users have defined an array of strings with different combinations: pickedStrings = ["A", "B", "G", "L", "Y"]; This can also be: pickedStrings = ["A", "G"] or pickedStrings = ["A", "L", "Y"] or any other mix. More strings may be added in the future. ...

Utilizing Typescript in tandem with an external library through es6 modules

Is there a recommended method for incorporating Typescript with non-module libraries like PixiJS and SortableJS without using webpacker? I'm looking to utilize es6 modules but want to avoid cumbersome solutions. What would be the best approach in this ...

How can you identify duplicate entries in a collection using Node.js?

I am trying to identify duplicate entries based on the "name" field and retrieve both the "name" and "_id" in the result. After attempting to use the aggregate function, all results from the database are returning as null: Below is the code snippet I hav ...

Displaying elements in a multi-dimensional array using PHP

After exploring numerous similar questions, I have yet to find a solution to my specific issue. In my database, I have a PHP nested array that needs to be printed in its entirety. The current output only displays the values of the topmost array ('name ...

Verify the attribute of the child element

In my child component, I have a property named files, which is an input type=file. This property allows me to determine if the user has selected a file for upload so that I can disable the submit button if no files are present in the input field. The issue ...