Putting Mongoose Validations to the Test: Using Jest's expect.toThrow

I'm looking to create a testing scenario to verify that if I forget to fill out a required field, the service will generate an error message.

Here is my schema:

export const UserSchema = new Schema({
    firstName: String,
    lastName: String,
    email: { type: String, required: true },
    passwordHash: String
});

And here is my service:

@Injectable()
export class UsersService {
    constructor(@InjectModel('User') private readonly userModel: Model<User>) {}

    async create(createUserDto): Promise<User> {
        const createdUser = new this.userModel(createUserDto);
        return await createdUser.save();
    }
}

Within my service test, I have the following case:

it('Validates email as required', async () => {
        const dto = {
            firstName: 'Test',
            lastName: 'User',
            passwordHash: '123ABC'
        };

        expect( async () => {
            return await service.create(dto);
        }).toThrowError(/required/);

    });

However, the test is not passing and I am receiving this error message:

    Expected the function to throw an error matching:
      /required/
    But it didn't throw anything.

Any suggestions on how to address this issue?

Answer №1

In order to enhance your test case, I would recommend making the following adjustment:

it('Validates required email', async () => {
        const dto = {
            firstName: 'John',
            lastName: 'Doe',
            passwordHash: '456XYZ'
        };

        await expect(service.create(dto)).rejects.toThrowError(ValidationError); //likely to result in this specific error

    });

Answer №2

Answer from personal experience. Utilizing expect.assertions along with try catch is key:

expect.assertions(1);
try {
    await user.register(data);
} catch (err) {
    expect(err.message).toMatch(/mandatory/);
}

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

What are the steps to integrate the isotope-layout into a next.js project?

I have been exploring the implementation of isotope-layout in a next.js project. To accomplish this, I referred to the following blog post: https://stackoverflow.com/questions/25135261/react-js-and-isotope-js. Additionally, I found a useful codesandbox lin ...

Utilizing an array of data to create a complex structure with nested

In my Next.JS React project using TSX files, I have set up a data file like this: const fieldMapping = { category:[ { title: "Category 1", Subtitle: ["Category 1", "Category 2"], SubSubTitle: ["Category ...

What is the purpose of mapping through Object.keys(this) and accessing each property using this[key]?

After reviewing this method, I can't help but wonder why it uses Object.keys(this).map(key => (this as any)[key]). Is there any reason why Object.keys(this).indexOf(type) !== -1 wouldn't work just as well? /** * Checks if validation type is ...

How do I go about utilizing or bringing in those constants within the Drawerr.js module?

Currently, working with Next.js, I have defined some constants in the Nav.js file: export default function NestedList() { const [value,setValue]=React.useState(); const theme=useTheme(); const isMatch=useMediaQuery(theme.breakpoints.down('lg&apo ...

Guidelines for converting an array into checkboxes using React Native with TypeScript

As I embark on my React Native journey, I have chosen to use TypeScript in my project. Currently, I am faced with the challenge of mapping an array into a checkbox. Enclosed below is a snippet from my JSON file: { "stud_name": "Adam", "sex": "male" ...

How do I correctly specify the parameter type of a function when passing a React functional component as an argument in TypeScript?

I am facing an issue with type declaration for function parameters. See the code snippet below, const FunctionalComponent = ({propA,propB}: FunctionalComponentProps): JSX.Element => { return } Now, I need to pass the FunctionalComponent as a parame ...

Angular 7: Resetting multiple dynamically generated checkboxes back to their original state with the click of a button

I have created a child component that contains 3 checkboxes, generated dynamically using ngFor, along with Apply and Cancel buttons. In the parent template, I include the selector tag for the child component. The parent component accesses this child compo ...

What is preventing me from importing moment into my TypeScript React Native project?

Looking to incorporate MomentJS into my ReactNative component with TypeScript. Successfully imported the library's d.ts file from the node_modules directory. This is how I am importing and utilizing the library: import * as moment from "moment"; con ...

The specified format of `x-access-token` does not match the required type `AxiosRequestHeaders | undefined`

I am encountering an issue while trying to add an authHeader to the "Service". The error message displayed is: Type '{ 'x-access-token': any; } | { 'x-access-token'?: undefined; }' is not assignable to type 'AxiosRequest ...

Retrieve a Targeted Value Across Numerous Arrays Using an Aggregation Filter

Here is the JSON response structure I am working with: { "_id": "5947e320d0f00f1794c87772", "selected_product": "5947e320d0f00f1794c87774", "sign_in_label": { "value": "Sign In", "translation": [ { " ...

What is the most effective way to display multiple variables simultaneously in Mongoose/Node.js?

As a newcomer to programming, my initial major project involves building a website using Mongoose and Node.js. I have a query regarding rendering two variables for ejs simultaneously without encountering an error due to attempting to render a query that h ...

Error message: `Socket.io-client - Invalid TypeError: Expected a function for socket_io_client_1.default`

I have successfully installed socket.io-client in my Angular 5.2 application, but after trying to connect (which has worked flawlessly in the past), I am encountering a strange error. TypeError: socket_io_client_1.default is not a function at new Auth ...

Having trouble with Angular2 Typescript and .NET Core in VS2015? Running into issues like not being able to locate names such as 'Promise', 'Set', and 'Map'?

I am currently following the Angular2 quickstart guide (https://angular.io/docs/ts/latest/quickstart.html) in order to develop a web application using Typescript and .NET Core. I have successfully resolved and generated dependencies and typings, however, u ...

Is it possible to use AngularJS promise scheduling with `async`/`await` syntax?

When working with AngularJS services, TypeScript often recommends that I switch my code to use async/await functions. https://i.sstatic.net/vks1i.png While I understand that using the await keyword is compatible with third-party promises because it essen ...

Encountering Compilation Error in @microsoft/mgt Graph Toolkit Upon Transition from Angular 11 to Angular 13

Previously, I had integrated the Microsoft toolkit into my Angular 11 application without any issues. However, when I was asked to upgrade to Angular 13 and updated the toolkit to its latest version (2.3.2 at the time of writing), I started encountering co ...

Angular 2 Application faces rejection by .NET API due to absence of "Access-Control-Allow-Origin"

How can I specify the content type as application/json format? I have a POST method that is used to add a customer's contact. I have created a WebAPI with the following code snippet... [Produces("application/json")] [Route("api/[controller]")] publi ...

What is the reason behind the prevalent use of the "pre" function with userSchema in conjunction with bcryptjs?

It's common to use the "pre" function with userSchema in bcrypt for express applications. This function is a middleware that runs before the .save() method to encrypt passwords. But what exactly is the reasoning behind using "pre" specifically with us ...

Nesting / Mulled / JS - Uploading Files - Form's end is unexpectedly reached

I have successfully implemented the upload file functionality in my Nest.js server application, but I am facing an issue when trying to use it with JavaScript/React. @Post('upload') @UseInterceptors(FileInterceptor('file')) upl ...

Deciphering the TypeScript type in question - tips and tricks

One of my abstract classes includes a static property with various properties, where default is consistently named while the others may have random names. public static data = { default: { //only this one always have 'dafault' name na ...

An error occured: Unable to access undefined properties (specifically 'hasOwnProperty')

I encountered an issue and managed to solve it. I am currently working on creating an update profile page for my Express app using Mongoose, but I keep getting the error "TypeError: Cannot read properties of undefined (reading 'hasOwnProperty')". ...