简体   繁体   中英

In a mocked function, how do I get the input parameters that were passed into it?

Let's say I have mocked out a function like this:

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

Within the body of the mocked implementation, how can I get a reference to the input parameters that were passed into foo ?

Maybe this will help:

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

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

The function you pass into mockImplementation will replace foo as far as the tests are concerned. So, if you want to use the parameters passed into foo , make sure the mock function has the same signature. If foo receives two arguments, for example, you'd call mockImplementation like this:

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

( arg1 and arg2 are just examples; you can name them however you want)

If you want to check the arguments that were passed into the function and match against expected arguments in your tests, you can use .toHaveBeenCalledWith (https://jestjs.io/docs/en/expect#tohavebeencalledwitharg1-arg2- ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM