Home > database >  "TypeError: _axios.default.get is not a function"
"TypeError: _axios.default.get is not a function"

Time:11-24

I try to write mock test using jest and @vue/test-utils, Here is the "bots.spec.js" / test file.

jest.mock('axios', ()=>({
  getBots: () => {
    const result = {
      __esModule: true,
      
      data: () => ({
        name: "demo",
        _id: "62e8d832afdaad001b65bff5",
      })
    }
    return Promise.resolve(result)
  }
}))

let getBots;
describe('Load bots function', () => {
  beforeEach(async () => {
    jest.clearAllMocks()

    getBots = (await import('../../src/services')).default
  })

  it('Should load given bots', async() =>{
    const bot_Name = "demo"
    const bot_id = "62e8d832afdaad001b65bff5"

    const actual = await getBots(bot_id)
    expect(actual).toMatch(bot_Name)
  })
})

Following error occurred

TypeError: _axios.default.get is not a function

screenshot of the occurred error

CodePudding user response:

You can mock like this and choose value returned later

jest.mock('axios', () => ({
  get: jest.fn(),
}));

The return value can be set like this

it('Should load given bots', async() =>{
  (mockAxios.get as jest.Mock).mockImplementationOnce(() =>
    Promise.resolve({
      data: {
        name: "demo",
        _id: "62e8d832afdaad001b65bff5",
      }
    })
  );
  const bot_Name = "demo"
  const bot_id = "62e8d832afdaad001b65bff5"

  const actual = await getBots(bot_id)
  expect(actual).toMatch(bot_Name)
})

CodePudding user response:

This is work for me

  jest.mock('axios', ()=>({
  get: () => {
    const result = {
      data:{
        name: "demo",
        _id: "62e8d832afdaad001b65bff5",
      }
    }
    return Promise.resolve(result)
  }
}))

let getBots;
describe('Load bots function', () => {
  beforeEach(async () => {
    jest.clearAllMocks()
    getBots = (await (await import('../../src/services')).getBots)
  })

  it('Should load given bots', async() =>{
    const expectedResponse = {
      name: "demo",
      _id: "62e8d832afdaad001b65bff5",

    }
    const actual = await getBots()

    expect(actual.data).toStrictEqual(expectedResponse)
  })
})
  • Related