如何得到 jest 模拟函数中调用的参数?
我想检查作为参数传递的对象。
只要使用 调用。在我的情况下,我使用:
const call = mockUpload.mock.calls[0][0]
这是 关于 mock属性的文档
mock
下面是断言传递的参数的一种简单方法。
expect(mockedFunction).toHaveBeenCalledWith("param1","param2");
我更喜欢 lastCalledWith()而不是 toHaveBeenCalledWith()。它们都是一样的,但前者更短,帮助我减少阅读代码时的认知负荷。
lastCalledWith()
toHaveBeenCalledWith()
expect(mockedFn).lastCalledWith('arg1', 'arg2')
可以将 toHaveBeenCalledWith()与 expect.stringContaining、 expect.arrayContaining()或 expect.objectContaining()一起使用
expect.stringContaining
expect.arrayContaining()
expect.objectContaining()
... const { host } = new URL(url); expect(mockedFunction).toHaveBeenCalledWith("param1", expect.stringContaining(`http://${host}...`);
我们可以向模拟方法添加一个模拟实现,并让它返回可用于计算的参数。