简体   繁体   中英

Difference between jest mockImplementation() and mockImplementationOnce()

I have been working with Jest mockImplementation() for quite some time now. I came across mockImplementationOnce() in jest. I read about it but I am not quite sure how it works. Can anyone mention an article that explains the difference? I can't seem to find anything specific.

Documentation

Based on the documentation, mockImplementation() accepts a function that should be used as the implementation of the mock. So, basically, you can mock a function by passing the function to it.

mockImplementationOnce() accepts a function that will be used as an implementation of the mock for one call to the mocked function. So, with this, one can mock the function once. It is also mentioned that it can be chained so that different result is returned for each Once call.

Below is an example of mockImplementationOnce() , from the documentation:

const myMockFn = jest.fn(() => 'default')
  .mockImplementationOnce(() => 'first call')
  .mockImplementationOnce(() => 'second call');

console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());
// 'first call', 'second call', 'default', 'default'

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