gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:18:20 26 4
gpt4 key购买 nike

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

我的注册方法是这样的:

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() 方法使用 stub 函数而不是调用实际的 Mongoose 数据库?

最佳答案

根据 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

})
})

希望对你有帮助

关于javascript - 如何模拟在我正在测试的函数内部调用的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51801027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com