【发布时间】:2019-01-18 23:41:08
【问题描述】:
尝试对我的 User mongoose 模型的 findOne 方法存根,但收到错误 Cannot stub non-existent own property findOne。
我在我的连接器中使用findOne 方法来获取用户并且效果很好。它只是在测试中说该方法不存在:
我可以这样调用 find 一个:
const user = await UserModel
.findOne({email: email})
.select(['hash', 'firstName', 'lastName', 'email'])
它会返回带有所选属性的我的用户。
当我尝试在我的测试中覆盖它时:
import UserModel from '../../models/user'
beforeEach(() => {
// ...
myStub = sinon
.stub(UserModel.prototype, 'findOne')
.callsFake(() => Promise.resolve(expectedUser))
})
sinon有什么理由会认为我的UserModel.prototype没有findOne()这个方法?
我的用户模型
import { isEmail } from 'validator';
import mongoose, { ObjectId } from 'mongoose';
import bcrypt from 'bcrypt';
const Schema = mongoose.Schema;
const UserSchema = new Schema({
firstName: { type : String, required : true },
lastName: { type : String, required : true },
email: { type: String, trim: true, lowercase: true, unique: true, required: 'Email address is required', validate: [ isEmail, 'invalid email' ] },
hash: { type : String, required : true, select: false },
refreshToken: { type : String, select: false },
});
// generate hash
UserSchema.methods.generateHash = (password) => bcrypt.hashSync(password, bcrypt.genSaltSync(8), null)
// checking if password is valid
UserSchema.methods.validPassword = (password, hash) => bcrypt.compareSync(password, hash)
export default mongoose.model('User', UserSchema);
【问题讨论】:
-
UserModel是变量吗?它看起来像一个类。在这种情况下,您必须写new UserModel。但如果它是一个变量而不是任何东西的实例,findOne 就不是UserModel.prototype的属性。 -
@UncreativeName 我已更新我的帖子以显示我的 userModel。它是猫鼬模型的一个实例
-
在我正在运行的其他测试中,我可以成功地存根 UserModel 的
.save()方法,所以我不确定.findOne()方法有什么不同。也许是因为我也打电话给.select()?
标签: javascript node.js mongoose mocking sinon