Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!