I'm trying this:
我正在尝试这个:
expect(AP.require).toBeCalledWith('messages', () => {})
where AP.require is a mocked function that should receive a string and a function as the second argument.
其中AP.require是一个模拟函数,它应该接收一个字符串,一个函数作为第二个参数。
Test fails with the message:
测试失败并显示以下消息:
Expected mock function to have been called with:
[Function anonymous] as argument 2, but it was called with [Function anonymous]
3 个解决方案
#1
11
To assert any function, you can you use expect.any(constructor)
:
要断言任何函数,您可以使用expect.any(构造函数):
So with your example it would be like this:
所以用你的例子就是这样的:
expect(AP.require).toBeCalledWith('messages', expect.any(Function))
#2
5
The problem is that a function is an object and comparing objects in JavaScript will fail if they are not the same instance
问题是函数是一个对象,如果它们不是同一个实例,那么比较JavaScript中的对象将会失败
() => 'test' !== () => 'test'
To solve this you can use mock.calls
to check the parameters seperataly
要解决这个问题,您可以使用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')
#3
0
You can use expect.any(constructor)
你可以使用expect.any(构造函数)
or if you do not care to specify the constructor, you can also use
或者如果您不关心指定构造函数,您也可以使用
expect.anything()
#1
11
To assert any function, you can you use expect.any(constructor)
:
要断言任何函数,您可以使用expect.any(构造函数):
So with your example it would be like this:
所以用你的例子就是这样的:
expect(AP.require).toBeCalledWith('messages', expect.any(Function))
#2
5
The problem is that a function is an object and comparing objects in JavaScript will fail if they are not the same instance
问题是函数是一个对象,如果它们不是同一个实例,那么比较JavaScript中的对象将会失败
() => 'test' !== () => 'test'
To solve this you can use mock.calls
to check the parameters seperataly
要解决这个问题,您可以使用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')
#3
0
You can use expect.any(constructor)
你可以使用expect.any(构造函数)
or if you do not care to specify the constructor, you can also use
或者如果您不关心指定构造函数,您也可以使用
expect.anything()