Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Trying to stub the findOne method of my User mongoose model but getting the error
Cannot stub non-existent own property findOne
.
I am using the
findOne
method in my connector to fetch the user and that works fine. It is only in the test it says the method doesn't exist:
I can call find one like so:
const user = await UserModel
.findOne({email: email})
.select(['hash', 'firstName', 'lastName', 'email'])
and it returns my user with the selected attributes.
When I try override it in my test:
import UserModel from '../../models/user'
beforeEach(() => {
// ...
myStub = sinon
.stub(UserModel.prototype, 'findOne')
.callsFake(() => Promise.resolve(expectedUser))
Is there any reason why sinon would think my UserModel.prototype
doesn't have the method findOne()
?
My user model
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 doesn't have findOne property neither as it's own property, nor in the prototype as soon as it inherits it from Model (mongoose.Model).
You can access original findOne method via UserModel.__proto__.findOne
.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.