0

I have a simple register() method which calls the mongoose save method

async register({firstName, lastName, email, password}){
    try {
        const salt = bcrypt.genSaltSync(10);
        const hash = bcrypt.hashSync(password, salt);

        return await new UserModel({
            firstName,
            lastName,
            email,
            hash
        }).save()

    }catch (err) {
        console.log(`Unable to register new user: ${err}`)
        throw 'Unable to register new user'
    }
}

When I call my register() method in my unit test, I want the mongoose save method to overwritten.

My unit test is as so:

import UserConnector from './user'

describe("User connector", () => {

    let userConnector

    beforeEach(() => {
        userConnector = new UserConnector()
    })

    it("should register user", () => {

        const expectedUser = {
            firstName: "adsfja",
            lastName: "adsfja",
            email: "adsfja@alsda.com",
            password: "password123"
        }

        var myStub = sinon.stub(UserModel.prototype, 'save').withArgs(expectedUser)

        const user = userConnector.register(expectedUser)

        expect(user).toEqual({
            firstName: "adsfja",
            lastName: "adsfja",
            email: "adsfja@alsda.com"
        })

    })
})

I have stubbed my mongoose save function but how do I tell my register() function to use the stubbed function instead of the default mongoose model save method?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Stretch0
  • 8,362
  • 13
  • 71
  • 133
  • You've already got Jest, it's capable of mocking functions, no Sinon is needed. `save` is prototype method. It can be mocked on `UserModel.prototype`. There's a chance that this is XY problem, and testing methodology is wrong; it's not `save` but any unit that is not a unit under test that should be mocked. It's likely entire UserModel that should be mocked, possibly with Jest module mocking. – Estus Flask Aug 11 '18 at 14:34
  • I do not believe the question you've stated is a duplicate of mine, is in fact a duplicate. I have reworded my question but I want to know how I can tell my `register` method to use the overwritten stubbed function instead of the default mongoose model save method. – Stretch0 Aug 11 '18 at 14:55
  • I marked it as a dupe because [this is the same question](https://stackoverflow.com/questions/28824519/stubbing-the-mongoose-save-method-on-a-model) and it got correct answers. It's unclear why you use Sinon considering that the question is labeled with jest; it may not work properly without additional setup. As I mentioned, Sinon is not needed. You don't need to 'tell' `register` method anything. `save` should be stubbed the way you're doing it. If it doesn't work, consider updating the question with your current attempt and the explanation what exactly is wrong, I'll remove dupe flag – Estus Flask Aug 11 '18 at 15:27

0 Answers0