I am currently facing an issue while trying to create a test scenario. The problem arises with the endpoint I have for a REST-API:
Post
represents a Mongoose model.
router.post('/addPost', (req, res) => {
const post = new Post(req.body);
post.save()
.then(() => ... return success)
.catch((err) => ... return error);
});
My goal is to write a test that verifies if the correct value is returned when save()
resolves.
After attempting to mock the save()
method within the model, I realized it may not be possible. As mentioned in this thread , save is not a method on the model itself but on the document (an instance of the model).
Even after following the recommended approach from the above-mentioned discussion, I seem to be missing something as I cannot successfully override the save()
method.
The code snippet I have so far (factory
is sourced from factory-girl as per the instructions provided in the given link. 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 believe my implementation might be off track, but I am unable to pinpoint where I am going wrong. There must be others who have encountered a similar issue before.