在模拟函数中,如何获取传递给它的输入参数?

问题描述

比方说,我已经嘲笑了一个像这样的函数

const foo = jest.fn().mockImplementation(() => { ... })

在模拟实现的主体中,如何获得对传递到foo的输入参数的引用?

解决方法

也许这会有所帮助:

const myMockFn = jest
  .fn()
  .mockImplementationOnce(cb => cb(null,true))
  .mockImplementationOnce(cb => cb(null,false));

myMockFn((err,val) => console.log(val));
// > true

myMockFn((err,val) => console.log(val));
// > false

来自:https://jestjs.io/docs/en/mock-functions#mock-implementations

,

就测试而言,您传递给mockImplementation的函数将替换foo。因此,如果要使用传递到foo中的参数,请确保模拟函数具有相同的签名。例如,如果foo收到两个参数,您将这样调用mockImplementation

const foo = jest.fn().mockImplementation((arg1,arg2) => {
 /* whatever you want to do with the arguments here */ 
})

({arg1arg2只是示例;可以根据需要命名)

如果要检查传递给函数的参数并与测试中的预期参数匹配,则可以使用 .toHaveBeenCalledWithhttps://jestjs.io/docs/en/expect#tohavebeencalledwitharg1-arg2-)。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...