问题描述
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 */
})
({arg1
和arg2
只是示例;可以根据需要命名)
如果要检查传递给函数的参数并与测试中的预期参数匹配,则可以使用
.toHaveBeenCalledWith
(https://jestjs.io/docs/en/expect#tohavebeencalledwitharg1-arg2-)。