user938363
user938363

Reputation: 10360

How to assert the validate error in sequelizejs unit test with jest?

I am unit testing a User model. The user name shouldn't be empty. The unit test is the following:

it('should reject no name', async () => {
   name = '';
   expect(await User.create(payload())).toThrow();
});

when payload has all the data except with empty name, the unit test throw the following error:

 SequelizeValidationError: Validation error: Invalid validator function: unique,
    Validation error: Invalid validator function: msg,
    Validation error: column "cell" does not exist

However the assertion here .toThrow is not right and the test case still fails. Tried toBeUndefined with no avail. What is the correct assertion for this type of error?

Upvotes: 1

Views: 1980

Answers (2)

Brian Adams
Brian Adams

Reputation: 45820

Assuming User.create returns a Promise that rejects with the thrown error:

await expect(User.create(payload())).rejects.toThrow();  // SUCCESS

Note that toThrow was fixed for promises with PR 4884 so if you are using an older version of Jest (before 22.0.0) you will need to use something like toEqual:

await expect(User.create(payload())).rejects.toEqual(expect.any(Error));  // SUCCESS

Upvotes: 5

Muhammad Aadil Banaras
Muhammad Aadil Banaras

Reputation: 1284

you need to do this.

await expect( User.create(payload())).to.be.rejectedWith(Error)

Now, test will pass if user.create throws error, & fail if it didn't throw the error.

Upvotes: 1

Related Questions