试图期望使用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.spyOn(),而不是手动用jest.fn()覆盖每个函数,因为它允许您在测试后通过调用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();
});

最新更新