"TypeError: _axios.default.get is not a function"



我尝试使用jest和@vue/test-utils编写模拟测试,这里是">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)
})
})

出现以下错误

TypeError: _axios.default.get is not a function

发生错误的截图

您可以这样模拟并选择稍后返回的值

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

返回值可以这样设置

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)
})

这是我的工作

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)
})
})

相关内容

最新更新