[英]Trying to expect a call to a function inside an anonymous function with JEST
我正在嘗試測試是否已調用console.warn
:
功能 :
trackError({ eventCategory, eventAction, eventLabel, errorResponse = false }) {
if (typeof window.ga !== 'undefined') {
window.ga('send', 'event', eventCategory, eventAction, eventLabel, {
hitCallback: () => {
if (errorResponse) {
console.warn(eventLabel + ' :: errorResponse => ', errorResponse)
} else {
console.warn(eventLabel)
}
}
})
}
}
測試:
it('should emit a console.warn with the eventLabel variable only', () => {
window.ga = jest.fn()
console.warn = jest.fn()
trackError({
eventCategory: 'PMC',
eventAction: 'error',
eventLabel: 'not found'
})
expect(window.ga).toHaveBeenCalledWith('send', 'event', 'PMC', 'error', 'not found', {
hitCallback: expect.any(Function)
})
// expect(window.ga).toHaveBeenCalledWith('send', 'event', 'PMC', 'error', 'not found', {
// hitCallback: jest.fn().mockImplementationOnce(() => {
// expect(console.warn).toHaveBeenCalledWith('not found')
// })
// })
})
與其用jest.fn()
手動覆蓋每個函數,您可能更想使用jest.spyOn()
,因為它允許您在測試后通過調用mockFn.mockRestore()
來恢復初始函數。
主要問題是您需要模擬window.ga()
實現以同步調用您的hitCallback()
。
it('should emit a console.warn with the eventLabel variable only', () => {
const ga = jest.spyOn(window, 'ga').mockImplementation(
(command, hitType, eventCategory, eventAction, eventLabel, { hitCallback }) => {
hitCallback();
}
);
const warn = jest.spyOn(console, 'warn').mockImplementation(
() => {}
);
trackError({
eventCategory: 'PMC',
eventAction: 'error',
eventLabel: 'not found'
});
expect(ga).toHaveBeenCalledWith('send', 'event', 'PMC', 'error', 'not found', {
hitCallback: expect.any(Function)
});
expect(warn).toHaveBeenCalledWith('not found');
ga.mockRestore();
warn.mockRestore();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.