如何期望一个函数调用另一个函数?

How to expect one function to call another function?

我正在尝试模拟一个函数调用,并希望它调用其中的另一个函数一次。

myFunctions.test.js

import { resetModal } from '../myFunctions.js';

describe('resetModal', () => {
  it('calls the clearSomethingInModal function', () => {
    const clearSomethingInModal = jest.fn();
    resetModal();
    expect(clearSomethingInModal.mock.calls.length).toBe(1);
  })
})

myFunctions.js

export resetModal() {
  clearSomethingInModal()
}

但是,Jest 输出显示它尚未被调用。我怎样才能最好地做到这一点?

您的方法不起作用,因为您仅在测试文件的上下文中模拟 clearSomethingInModal,因此 myFunctions.js 中的 clearSomethingInModal 仍然是原始的。要点是你不能模拟在 myFunctions.js 中直接创建的东西。您唯一可以模拟的是:

  1. 您导入到 myFunctions.js 的模块,例如 import clearSomethingInModal from 'clearSomethingInModal'
  2. 从测试调用函数时传递给函数的回调;

如果您将 myFunctions.js 视为一个黑盒,这是有道理的,您可以在其中控制输入的内容(如导入或函数参数),以及可以测试输出的内容。但是您无法测试盒子内发生的事情。

这里有两个例子反映了列表中的 2 个点:

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

import clearSomethingInModal from 'clearSomethingInModal';

export resetModal() {
  clearSomethingInModal()
}

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

export resetModal(clearSomethingInModal) {
  clearSomethingInModal()
}

另一种方法是使用 done 并模拟或监视最后一个函数的实现,然后检查之前的函数是否被调用。

it('should call function2 after function1', (done) => {
    expect.assertions(2)

    function2.mockImplementationOnce(() => {
      expect(function1).toHaveBeenCalled()
      done()
    })

    act() // This is where you run function you are testing
  })

这个解决方案的缺点是测试的结构不是

// arrange
// act
// assert

而是

// arrange & assert
// act