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

236
Views
Can we mock function which is calling axios function inside without mocking axios in JEST for nodejs code

Please refer below code. Server.js code which is calling an API enclosed in loadUser function and called by fullNameGen function to create full name

const axios = require('axios');

function loadUser(){
    return new Promise((resolve,reject)=>{
        console.log("Load user called");
        axios.get('https://reqres.in/api/users/2').then((response)=>{
            resolve(response);
        }).catch((err)=>{
            reject(err);
        })
    })
    
}

function fullNameGen(){
    return new Promise((res,rej)=>{
        loadUser().then(({data:info})=>{
            console.log(info.data);
            res(info.data.first_name+" "+info.data.last_name);
        }).catch((err)=>{
            console.log(err.message);
            rej(err.message);
        })
    })
    
}

module.exports={
    fullNameGen:fullNameGen,
    loadUser:loadUser
}

And in server.test.js file I am trying to mock loadUser function not the axios directly. But the test still calling axios with the API .

server.test.js

const axios = require('axios');
const server = require('./server');

test("Check full Name generation",async()=>{
    server.loadUser=jest.fn();
    server.loadUser.mockResolvedValue={
        data:{
            data:{
            first_name:"rav",
            last_name:"shekhar"
        }}
    };
    const result = await server.fullNameGen();

    expect(result).toBe("ravi shekhar");
    expect(server.fullNameGen).toBeCalledTimes(1)
})

Please tell me why this test is giving error expect(received).toBe(expected) // Object.is equality

Expected: "ravi shekhar"
Received: "Janet Weaver"

  28 |     const result = await server.fullNameGen();
  29 |
> 30 |     expect(result).toBe("ravi shekhar");
     |                    ^
  31 |     expect(server.fullNameGen).toBeCalledTimes(1)
  32 | })

  at Object.<anonymous> (server.test.js:30:20)
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!