在下面的函数中,我必须模拟httpGet函数,因此应该调用模拟函数而不是调用实际函数并返回值
getStudents: async(req,classId) => {
let result = await httpGet(req);
return result;
},
我的测试用例
describe('Mock',()=>{
it('mocking api',async()=>{
const result = await getStudents(req,classId);;
console.log(result);
})
})
答案 0 :(得分:0)
对于该函数的模拟,您可以拥有与普通函数相同的jest.fn()
。
然后,您可以实现自己的Promise返回值,也可以使用笑话的mockResolvedValue
或mockRejectedValue
https://jestjs.io/docs/en/mock-function-api#mockfnmockresolvedvaluevalue
例如:
import { httpGet } from 'http';
jest.mock('http'); // this is where you import the httpGet method from
describe('Mock',()=>{
it('mocking api',async() => {
httpGet.mockResolvedValue(mockresult); // httpGet should already be a jest.fn since you used jest.mock
const result = await getStudents(req,classId);
console.log(result);
})
})