Javascript 尝试使用JEST在匿名函数中调用函数

Javascript 尝试使用JEST在匿名函数中调用函数,javascript,unit-testing,jestjs,Javascript,Unit Testing,Jestjs,我正在尝试测试是否调用了控制台。warn: 功能: trackError({eventCategory,eventAction,eventLabel,errorResponse=false}){ if(typeof window.ga!==“未定义”){ window.ga('send','event',eventCategory,eventAction,eventLabel{ hitCallback:()=>{ 如果(错误响应){ console.warn(eventLabel+'::erro

我正在尝试测试是否调用了
控制台。warn

功能:

trackError({eventCategory,eventAction,eventLabel,errorResponse=false}){
if(typeof window.ga!==“未定义”){
window.ga('send','event',eventCategory,eventAction,eventLabel{
hitCallback:()=>{
如果(错误响应){
console.warn(eventLabel+'::errorResponse=>',errorResponse)
}否则{
console.warn(事件标签)
}
}
})
}
}
测试:

it('应仅使用eventLabel变量发出console.warn',()=>{
window.ga=jest.fn()
console.warn=jest.fn()
跟踪误差({
事件类别:“PMC”,
eventAction:'错误',
eventLabel:“未找到”
})
expect(window.ga).toHaveBeenCalledWith('send'、'event'、'PMC'、'error'、'notfound'{
hitCallback:expect.any(函数)
})
//expect(window.ga).toHaveBeenCalledWith('send'、'event'、'PMC'、'error'、'notfound'{
//hitCallback:jest.fn().mockImplementationOnce(()=>{
//expect(console.warn).tohavencalledwith('notfound')
//     })
// })
})

您可能希望改用,而不是使用手动覆盖每个函数,因为它允许您在测试后通过调用恢复初始函数

主要问题是需要模拟
window.ga()
实现来同步调用
hitCallback()

it('应仅使用eventLabel变量发出console.warn',()=>{
const ga=jest.spyOn(窗口'ga').mock实现(
(命令,hitType,eventCategory,eventAction,eventLabel,{hitCallback})=>{
hitCallback();
}
);
const warn=jest.spyOn(控制台“warn”).mock实现(
() => {}
);
跟踪误差({
事件类别:“PMC”,
eventAction:'错误',
eventLabel:“未找到”
});
expect(ga).toHaveBeenCalledWith('send'、'event'、'PMC'、'error'、'notfound'{
hitCallback:expect.any(函数)
});
期望(警告)。与('notfound')一起调用;
ga.mockRestore();
warn.mockRestore();
});