Stretch0
Stretch0

Reputation: 9285

How do I mock a function that is called inside the function I am testing?

I have a register function which saves my user to the mongoose DB. When testing, I don't want the user to actually get saved to the DB so I want to override the mongoose save method.

My register method is as so:

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'
    }
}

So I want to test this method. I have written the test but I don't know how I pass the mocked function into my register() function

import UserConnector from './user'
import sinon from 'sinon'
import mongoose from 'mongoose'
import UserModel from '../../models/user'

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

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

        const expectedUser = {
            firstName: "adsfja",
            lastName: "adsfja",
            email: "[email protected]",
            password: "password123"
        }

        var myStub = sinon.stub(UserModel.prototype, 'save').withArgs(expectedUser) // <--- How can I pass this into my userConnector.register() method so that the stub is called instead of the real thing

        const user = new UserConnector().register(expectedUser)

        expect(user).toEqual({
            firstName: "adsfja",
            lastName: "adsfja",
            email: "[email protected]"
        })

    })
})

How can I tell my register() method to use the stubbed function instead of calling the actual mongoose DB?

Upvotes: 2

Views: 1213

Answers (1)

Theo
Theo

Reputation: 2042

As per documentation, the way to achieve this is using callsFake

See example below

import UserConnector from './user'
import sinon from 'sinon'
import mongoose from 'mongoose'
import UserModel from '../../models/user'

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

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

        const expectedUser = {
            firstName: "adsfja",
            lastName: "adsfja",
            email: "[email protected]",
            password: "password123"
        }

        var myStub = sinon
          .stub(UserModel.prototype, 'save')
          .callsFake(() => Promise.resolve(expectedUser))

        const userConnector = new UserConnector();
        // since register is used as async, we should expect it to return a promise
        const user = await userConnector.register(expectedUser)

        expect(user).toEqual({
            firstName: "adsfja",
            lastName: "adsfja",
            email: "[email protected]"
        })
        myStub.restore() // don't forget to restore stubbed function

    })
})

Hope this helps

Upvotes: 2

Related Questions