【问题标题】:Using Jest, how can I check that an argument to a mocked function is a function?使用 Jest,我如何检查模拟函数的参数是否是函数?
【发布时间】:2018-04-04 01:15:20
【问题描述】:

我正在尝试这个:

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]

【问题讨论】:

    标签: node.js jestjs


    【解决方案1】:

    问题是函数是一个对象,如果它们不是同一个实例,那么在 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')
    

    【讨论】:

    • 这个答案对我有帮助,谢谢安德烈亚斯。我认为第一行应该是const call = AP.require.mock.calls[0]
    【解决方案2】:

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

    所以你的例子是这样的:

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

    【讨论】:

    • 漂亮的解决方案!
    • 对某些人来说可能很明显,但仍然值得指出您可以使用任何其他构造函数(例如Number、Object 等)
    • 如果第二个参数是可选的,还有expect.anything()。
    • @Rohmer 如果第二个参数是可选的,您可能应该添加一个额外的测试。
    猜你喜欢
    • 2019-12-01
    • 2019-09-23
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    相关资源
    最近更新 更多