Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

244
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda