I am running into an issue trying to write a test. I got the following endpoint for a REST-API:
Post
is a Mongoose model.
router.post('/addPost', (req, res) => {
const post = new Post(req.body);
post.save()
.then(() => ... return success)
.catch((err) => ... return error);
});
I would like to write a test to check if an the correct value is returned to the user when save()
resolves.
I tried to mock the save()
method in the model but this does not seem possible. As described here https://stackoverflow.com/a/34666488/10754437, save is not a method on the model, it's a method on the document (instance of a model).
I tried testing it as described in that post but I must be going at it the wrong way as I still can't manage to overwrite the save()
method correctly.
I currently have this code (factory
comes from factory-girl as described in the link I tried to use to solve this issue. Here is a direct link to the package):
factory.define('Post', Post, {
save: new Promise((resolve, reject) => {
resolve();
}),
});
factory.build('Post').then((factoryPost) => {
Post = factoryPost;
PostMock = sinon.mock(Post);
PostMock.expects('save').resolves({});
... perform test
});
I am guessing I am doing this horribly wrong but I cannot figure out what I am missing. I am guessing someone must have ran into this before.