如何模拟正在测试的函数内部调用的函数?

时间:2018-08-11 15:11:06

标签: javascript node.js unit-testing mongoose jestjs

我有一个注册功能,可以将用户保存到猫鼬数据库中。测试时,我不希望用户实际保存到数据库中,所以我想重写猫鼬保存方法。

我的注册方法如下:

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

所以我想测试这个方法。我已经编写了测试,但不知道如何将模拟的函数传递到register()函数中

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: "adsfja@alsda.com",
            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: "adsfja@alsda.com"
        })

    })
})

如何告诉我的register()方法使用存根函数而不是调用实际的猫鼬数据库?

1 个答案:

答案 0 :(得分:1)

根据documentation,实现此目标的方法是使用callsFake

请参见下面的示例

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: "adsfja@alsda.com",
            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: "adsfja@alsda.com"
        })
        myStub.restore() // don't forget to restore stubbed function

    })
})

希望这会有所帮助