使用 Jest,我如何检查模拟函数的参数是否是函数



我正在尝试这个:

expect(AP.require).toBeCalledWith('messages', () => {})

其中 AP.require 是一个模拟函数,应该接收一个字符串和一个函数作为第二个参数。

测试失败,并显示以下消息:

Expected mock function to have been called with:
  [Function anonymous] as argument 2, but it was called with [Function anonymous]

要断言任何函数,您可以使用expect.any(constructor)

所以用你的例子,它会是这样的:

expect(AP.require).toBeCalledWith('messages', expect.any(Function))

问题是函数是一个对象,如果它们不是同一个实例,则在 JavaScript 中比较对象将失败

() => 'test' !== () => 'test'

要解决此问题,您可以使用mock.calls单独检查参数

const call = AP.require.mock.calls[0] // will give you the first call to the mock
expect(call[0]).toBe('message')
expect(typeof call[1]).toBe('function')

最新更新