I want to test this function using jest. here is my code-
templeate.ts
export const generateSalamWelcome = async function (
actionSource: IActionSource,
actionDetails: IActionDetails
): Promise<IReplyTemplate[] | undefined> {
try {
const { pageId } = actionSource;
const { actionExt } = actionDetails;
const restaurantData = await getRestaurantQueriesMultiple(pageId, []);
if (restaurantData) {
const replyTemplates: IReplyTemplate[] = [];
const { enOnly, bnOnly } = restaurantData;
const mode = getMode(enOnly, bnOnly, actionExt || languageModes.EN);
replyTemplates.push(
generateTextTemplate(
selectTextEnBn(mode, strings.salamWelcomeEn, strings.salamWelcomeBn)
)
);
return replyTemplates;
}
} catch (err) {
logger.error(err);
}
};
I want to mock getRestaurantQueriesMultiple, getMode and generateTextTemplate functions. How do I mock them properly to return some dummy result?
CodePudding user response:
You can make use of mockImplementation()
in jest. With this you can spyOn()
on a class method or a function in a file. For example in your case, let's consider a filename MyFile.ts
in which you have exported the function getMode()
. If your getMode()
exists in the same file template.ts
then dont consider file name as MyFile
, instead go with template.ts
. So, inside your it
block you could do something like this,
const dummyResult = 'dummyData';
jest.spyOn(MyFile, 'getMode')
.mockImplementation(() => {
return Promise.resolve(dummyResult);
})
Similarly you can do the same for getRestaurantQueriesMultiple()
and generateTextTemplate()
. But make sure you mock all these functions before you make a call to the actual function, which in your case is generateSalamWelcome()
You can read more about mockImplementation()
here Jest Mock Implementation