[英]Trying to expect a call to a function inside an anonymous function with JEST
I'm trying to test that a call to console.warn
has been made :我正在尝试测试是否已调用
console.warn
:
Function :功能 :
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)
}
}
})
}
}
Test:测试:
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')
// })
// })
})
Rather than manually overwriting each of the functions with a jest.fn()
, you probably want to use jest.spyOn()
instead, since it allows you to restore the initial functions after the test by calling mockFn.mockRestore()
.与其用
jest.fn()
手动覆盖每个函数,您可能更想使用jest.spyOn()
,因为它允许您在测试后通过调用mockFn.mockRestore()
来恢复初始函数。
The main issue is that you need to mock the window.ga()
implementation to synchronously invoke your hitCallback()
.主要问题是您需要模拟
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.