【问题标题】:Cannot stub non-existent own property findOne无法存根不存在的自有属性 findOne
【发布时间】: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


【解决方案1】:

UserModel 没有 findOne 属性,既不是它自己的属性,也没有从 Model 继承的原型中(猫鼬模型)。 您可以通过UserModel.__proto__.findOne 访问原始 findOne 方法。

【讨论】:

    猜你喜欢
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 2018-05-05
    • 1970-01-01
    • 2017-08-25
    • 2017-07-11
    • 1970-01-01
    相关资源
    最近更新 更多