Home > Blockchain >  Jest doesn't catch error, when thrown from async/await function
Jest doesn't catch error, when thrown from async/await function

Time:03-30

Im testing some functions with MongoDB and Mongoose. For the tests i'm using Jest and mongo-memory-server. The function createUser(arg1, arg2) should throw a TypeError if there already exists a user with that discord id in the database.

createUser(arg1, arg2)

async function createUser(disc_id, moodleToken) {
    const profileData = await fetchUser(disc_id);
    
    if (profileData) {
        throw TypeError("The account already exist in the database!");
    }
    const newUser = new profileModel({
        discord_id: disc_id,
        moodle_token: moodleToken,
    })
    
    await newUser.save();
        
    return {
        userId: newUser._id
    };
} 

fetchUser(disc_id) returns whether a user with the same discord id is found or not.

When testing with Jest i created the following test which passes just fine:

it("Should create a new user", async () => {
        const discord_id = "3452357445";
        const moodle_token = "34ffDSE8439Ujfe8f3jj";

        const { userId } = await createUser(discord_id, moodle_token);

        const user = await profileSchema.findById(userId);

        expect(user.discord_id).toEqual(discord_id);
        expect(user.moodle_token).toEqual(moodle_token);
        
    })

Now i want to test if the TypeError is thrown when trying to create a new user, with the same discord id, i tried the following without any success:

describe("Error when", () => {
        it("an existing matches discord id", async () => {
            const discord_id = "3452357445";
            const moodle_token = "34ffDSE8439Ujfe8f3jj";
            
            await createUser(discord_id, moodle_token)

            await expect(async () => {
                createUser(discord_id, moodle_token);
            }).rejects.toThrow(TypeError("The account already exist in the database!"))           
        })
    })

When running the tests this is the output from the console:

 FAIL  test/manageUserDB.test.js
  Create new user
    ✓ Should create a new user (66 ms)
    Error when
      ✕ an existing matches discord id (3 ms)

  ● Create new user › Error when › an existing matches discord id

    TypeError: The account already exist in the database!

      11 |     
      12 |     if (profileData) {
    > 13 |         throw TypeError("The account already exist in the database!");
         |               ^
      14 |     }
      15 |     const newUser = new profileModel({
      16 |         discord_id: disc_id,

      at createUser (BoodleDB/manageUserDB.js:13:15)
      at Object.<anonymous> (test/manageUserDB.test.js:29:13)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        0.6 s, estimated 1 s
Ran all test suites matching /.\/test/i.

EDIT

function fetchUser (disc_id) {
    return profileModel.findOne({ discord_id: disc_id });
}

CodePudding user response:

You need to await when you call createUser.

await expect(async () => {
  await createUser(discord_id, moodle_token);
}).rejects.toThrow(TypeError("The account already exist in the database!")) 
  • Related