Skip to content

Commit

Permalink
handle save hook (#45)
Browse files Browse the repository at this point in the history
Updates #8
  • Loading branch information
hirochachacha authored and alonronin committed Dec 14, 2018
1 parent 1161405 commit b63215e
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 6 deletions.
9 changes: 6 additions & 3 deletions ___tests___/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ const { Schema } = mongoose;
const schema = Schema({
name: String,
email: { type: String, required: true },
created: { type: Date, default: Date.now }
created: { type: Date, default: Date.now },
saveCount: { type: Number, default: 0}
});

schema.pre('save', function() {
this.saveCount++
})

const User = mongoose.model('User', schema);

export default User;


18 changes: 17 additions & 1 deletion ___tests___/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,23 @@ describe('mockingoose', () => {
});
});
});

it(`save calls its hook correctly`, () => {
const mocked = {
name: 'save',
email: '[email protected]'
};

mockingoose.User.toReturn(null, 'save');

User.create(mocked).then(user => {
expect(user.saveCount).toBe(1);
user.name = 'save2';
user.save((err, user) => {
expect(user.saveCount).toBe(2);
})
});
});
});

describe('check all operations', () => {
Expand Down Expand Up @@ -496,4 +513,3 @@ describe('mockingoose', () => {
});
});
});

39 changes: 37 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,43 @@ instance.forEach(methodName => {

Object.assign(this, { op, model: { modelName } });

return mockedReturn.call(this, cb);
})
const hooks = this.constructor.hooks

return new Promise((resolve, reject) => {
hooks.execPre(op, this, [cb], (err) => {
if (err) {
reject(err);
return;
}

const ret = mockedReturn.call(this, cb);

if (cb) {
hooks.execPost(op, this, [ret], (err) => {
if (err) {
reject(err);
return;
}

resolve(ret);
});
} else {
ret
.then((ret) => {
hooks.execPost(op, this, [ret], (err) => {
if (err) {
reject(err);
return;
}

resolve(ret);
});
})
.catch(reject);
}
});
});
});
});

jest.doMock('mongoose', () => mongoose);
Expand Down

0 comments on commit b63215e

Please sign in to comment.