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

aze*_*eez 21 node.js jestjs

我正在尝试这个:

expect(AP.require).toBeCalledWith('messages', () => {})
Run Code Online (Sandbox Code Playgroud)

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

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

Expected mock function to have been called with:
  [Function anonymous] as argument 2, but it was called with [Function anonymous]
Run Code Online (Sandbox Code Playgroud)

Koe*_*en. 43

要断言任何功能,您可以使用expect.any(constructor):

所以用你的例子就是这样的:

expect(AP.require).toBeCalledWith('messages', expect.any(Function))
Run Code Online (Sandbox Code Playgroud)

  • 漂亮的解决方案! (2认同)
  • 对于某些人来说可能是显而易见的,但仍然值得指出,您可以使用任何其他构造函数(例如“Number”、“Object”等) (2认同)

And*_*rle 12

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

() => 'test' !== () => 'test'
Run Code Online (Sandbox Code Playgroud)

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

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')
Run Code Online (Sandbox Code Playgroud)

  • 这个答案对我有所帮助,谢谢安德里亚斯。我认为第一行应该是`const call = AP.require.mock.calls [0]` (2认同)