'Javascript Jest MockImplementation : mocking values in a called function
I'm trying to test my backend's methods (to check users quota, like if they can use the app) and I have some trouble with a specific one. Indeed I have a function that calls all my methods and procedes to give me the data that I want.
I can test different configuration with Jest by using mockImplementation on my methods.
But here is my problem, one of my function calls another function that give the user's quota from my db :
export async function getQuota(user_id) {
return await Quota.find({ user_id: user_id }).exec();}
//return a quota with its data (conso, user, date...)
export async function checkIfQuotaIsGood(user_id, date) {
let quota;
let quotas = await getQuotasByUserId(user_id);
//this method can sen error messages if quota received is not good or too small, too old ...
In every test i used to mock checkIfQuotaIsGood and say whether it is good or not:
...
checkIfQuotaIsGood.mockImplementation(() =>
Promise.resolve({
conso: 0,
user_id: user_id,
begin: "1614553200000",
end: "1617141600000",
quota: 100,
})
);
...
await mainFunction(req, res, next); //the function that executes all my methods, it calls checkIfQuotaIsGood which calls getQuota
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith({
mainFunction: true,
My problem is: in my function checkIfQuotaIsGood i have conditions on the quota getQuota send me. I want to mock my function getQuota and let my mainFunction call checkIfQuotaIsGood which will execute with the mock values. I tried to mock getQuota but when my mainFunction calls checkIfQuotaIsGood this function will call getQuota instead of using the mock values.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|