问题描述
我正在尝试模拟一个函数调用,并期望它曾经在其中调用另一个函数.
I am trying to mock a function call, and expect it to have called another function within it once.
myFunctions.test.js
myFunctions.test.js
import { resetModal } from '../myFunctions.js';
describe('resetModal', () => {
it('calls the clearSomethingInModal function', () => {
const clearSomethingInModal = jest.fn();
resetCreationModal();
expect(clearSomethingInModal.mock.calls.length).toBe(1);
})
})
myFunctions.js
myFunctions.js
export resetModal() {
clearSomethingInModal()
}
但是,Jest输出显示尚未调用它.如果有人可以建议如何最好地做到这一点,我将非常感激.
However, Jest output says that it has not been called. If anyone can suggest how best to do this, I would be very grateful.
推荐答案
您的方法不起作用,因为仅在测试文件的上下文中模拟了clearSomethingInModal
,因此myFunctions.js
中的clearSomethingInModal
仍然是原始的.要点是,您不能模拟直接在myFunctions.js
中创建的内容.您唯一可以嘲笑的是:
Your approach does not work because you mock clearSomethingInModal
only in the context of your test file, so clearSomethingInModal
in the myFunctions.js
is still the original. The main point is that you can't mock something that is directly created in myFunctions.js
. The only thing that you can mock are:
- 导入到
myFunctions.js
的模块,例如import clearSomethingInModal from 'clearSomethingInModal'
; - 从测试中调用函数时传递给函数的回调;
- Modules that you import to
myFunctions.js
, likeimport clearSomethingInModal from 'clearSomethingInModal'
; - Callbacks that you pass into your function when calling them from your test;
如果您将myFunctions.js
视为一个黑盒,这很有意义,您可以在其中控制输入内容(如导入或函数参数),并在其中测试结果.但是您无法测试盒子内部发生的事情.
This makes sense if you think about myFunctions.js
as a blackbox, where you can control what goes in, like imports or function arguments, and where you can test what comes out. But you can not test the stuff that happens inside the box.
下面是两个反映列表中两点的示例:
Here are two example that reflect the 2 points in the list:
myFunctions.test.js
myFunctions.test.js
import { resetModal } from '../myFunctions.js';
import clearSomethingInModal from 'clearSomethingInModal';
jest.mock('clearSomethingInModal', () => jest.fn())
describe('resetModal', () => {
it('calls the clearSomethingInModal function', () => {
resetCreationModal();
expect(clearSomethingInModal.mock.calls.length).toBe(1);
})
})
myFunctions.js
myFunctions.js
import clearSomethingInModal from 'clearSomethingInModal';
export resetModal() {
clearSomethingInModal()
}
myFunctions.test.js
myFunctions.test.js
import { resetModal } from '../myFunctions.js';
describe('resetModal', () => {
it('calls the clearSomethingInModal function', () => {
const clearSomethingInModal = jest.fn();
resetCreationModal(clearSomethingInModal);
expect(clearSomethingInModal.mock.calls.length).toBe(1);
})
})
myFunctions.js
myFunctions.js
export resetModal(clearSomethingInModal) {
clearSomethingInModal()
}
这篇关于开玩笑-模拟函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!