Exploring the functionality of a REST API created with express and mongoose, I am utilizing jest and supertest for handling http calls. Despite being new to testing in javascript, I am eager to learn.
Specifically when testing a creation URL, my goal is to ensure that the instantiation is done solely using the req.body object. After researching about mock objects versus stubs and studying Jest documentation, my latest attempt resembles the following:
test('Should correctly instantiate the model using req.body', done => {
const postMock = jest.fn();
const testPost = {
name: 'Test post',
content: 'Hello'
};
postMock.bind(Post); // <- Post represents my model
// Mocking the save function to avoid database usage
Post.prototype.save = jest.fn(cb => cb(null, testPost));
// Making the Supertest call
request(app).post('/posts/')
.send(testPost)
.then(() => {
expect(postMock.mock.calls[0][0]).toEqual(testPost);
done();
})
.catch(err => {throw err});
});
Furthermore, I am interested in understanding how to deliberately fail a test upon promise rejection, preventing the error message
Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
from appearing.