mock axios本质上就是mock axios的返回值,让其返回值取代真实的返回值,官网给的写法如下
import axios from 'axios';
import Users from './users';
jest.mock('axios');
test('should fetch users', () => {
const users = [{name: 'Bob'}];
const resp = {data: users};
axios.get.mockResolvedValue(resp);
// or you could use the following depending on your use case:
// axios.get.mockImplementation(() => Promise.resolve(resp))
return Users.all().then(data => expect(data).toEqual(users));
});
但是在正式使用的时候会报错:mockResolvedValue不是一个函数。
其实就是get当中没有这样的一个属性吧,可以这样解决
jest.mock('axios');
test("3",async()=>{
// 测试一下axios的mock
const users = [{name: 'Bob'}];
const resp = {data: users};
axios.get=jest.fn().mockResolvedValue(resp);
// (axios.get as any).mockImplementation(() => Promise.resolve(resp))
let res=await getAxios()
expect(res).toEqual(users)
})
忘记了,getAxios的内容是这样的
import axios from "axios";
export const getAxios = async () => {
const res = await axios.get('/api');
return res.data;
}
实际上就是把get重新赋值了吧,此外下面那种注释掉的写法也是可以的。
更新:这样的写法其实也挺好的
jest.spyOn(axios, 'get').mockResolvedValue({ data: { id: 2, name: 'User' } })