alonronin/mockingoose

Problem with invoking `this.model('ModelName')` inside model hook.

Closed this issue · 1 comments

It's impossible to use this.model('ModelName') in a model hooks Model.prototype.model().

For instance:

const schema = new mongoose.Schema({ name: String });
schema.pre('save', function(next) {
  this.model('ModelName'); // throw an error TypeError: this.model is not a function
});

I guess it's related to this code on line 267, where an object is assigned to the model property.

mockingoose/src/index.ts

Lines 256 to 269 in cc160bc

instance.forEach(methodName => {
mongoose.Model.prototype[methodName] = jest
.fn()
.mockImplementation(function(options, cb) {
const op = methodName;
const { modelName } = this.constructor;
if (typeof options === 'function') {
cb = options;
}
Object.assign(this, { op, model: { modelName } });
const hooks = this.constructor.hooks;

Is it possible to use other property name to store { modelName } object, e.g. __model?

you are correct this.model is not a function.

if you can provide a PR for this, it would be great!