I'm new to Jest and code testing in general. I would like to test a function that retrieves data from a mongodb database using mongoose. When I run the test all the calls to the db inside the function I'm testing return null. What's the recommended way to test functions that need to retrieve data from a database?
Let me know if you need code samples or more information.
Update:
Here's my code:
code.js
...
function buildText(listing, messageRule, reservation, isReview = false, isLastMinuteMessage = false) {
return new Promise(async function(resolve) {
const name = reservation.name;
try {
message = await Message.findOne({
listingID: listing._id,
messageRuleID: messageRule._id,
reservationID: reservation._id,
message: {$exists: true}
});
} catch (error) {
console.error(error);
}
if (message) {
text = message.message;
} else {
text = messageRule.message;
if (isLastMinuteMessage) {
text = messageRule.lastMinuteMessage;
}
}
text = text.replace(/{{Guest Name}}/g, name);
resolve(text);
});
}
...
code.test.js
const Code = require("./code");
describe("funcs", () => {
it("buildText", async () => {
let listing = {
_id: "1324",
pricingEnabled: true,
listingFound: true,
hideListing: null
};
let messageRule = {
_id: "3452345",
minNights: 1,
reviewEnabled: false,
disableMessageAfterReview: false,
message: 'test',
lastMinuteMessage: 'test2'
};
let reservation = {
_id: "63452345",
hasLeftReview: true,
hasIssues: false
};
let isReview = false;
let isLastMinuteMessage = false;
let response = await Code.buildText(listing, messageRule, reservation, isReview, isLastMinuteMessage);
expect(response).toMatchSnapshot();
});
});
The trouble I'm having is with the message = await Message.findOne({ line in my code file. It always returns null but I need to be able to tell it to return true or false. How can I do that?