DEV Community

ImTheDeveloper
ImTheDeveloper

Posted on

Help with Jest: How to test the error routes in my code?

I have the following static function within my ES6 User class which searches for a user given a string.

    // Search for a user by their pNick, includes partial matching
        static getBypNick(pNick = '') {
            // Define our search criteria regex and normalise to lower case
            const userSearchRegex = new RegExp(`^${pNick.toLowerCase()}`, 'i')

            return new Promise((resolve, reject) => {

                // Search user collection for pNick using regex like search and return array of results
                userTable.find({
                    _pNick: userSearchRegex
                }).sort({
                    _pNick: 1
                }).exec(function (err, result) {

                    // If error reject
                    if (err) {
                        return reject(err)
                    }
                    const userArray = result.map((user) => {
                        return new User(
                            user._pNick,
                            user._firstName,
                            user._userName,
                            user._phoneNumber,
                            user._userID)
                    })
                    // Return user records if found
                    return resolve(userArray)
                })
            })
        }
Enter fullscreen mode Exit fullscreen mode

Whilst I can easily test the success routes using Jest I'm struggling to understand how I can invoke the error cases, especially around the .exec method within the function to invoke my reject routes in the promise.

I understand that I can use various Jest features such as mocks and forcing implementation/return value but I just can't figure it all out and the best case in this scenario. The database being used behind the scenes is NeDB, I'm pretty positive I just need to force the .exec portion to return an error and then I should be catching this in my promise.

I have no intention of testing the underlying NeDB library as it has its own tests which execute successfully so this is really all about my own methods.

My coverage thus far:
Code Coverage

Top comments (0)