简体   繁体   中英

What is the difference between Jest Mock functions and Sinon spies

I am mocking a function with Jest and the documentation says they are really 'spies'. I have also seen the use of spies in SinonJS but I could find no clear difference between the two. If they are serving the same purpose, is there any reason to choose one over the other?

Jest Mock Functions

SinonJS

The main behaviour of both is the same, they are functions that can remember their calls. So for both you can figure out how often they were called and with which arguments. Sinon has a much wider API for what you can test on spies, and it has an API to replace functions in objects with spies.

I have found a caveat when using Sinon Vs Jest. In my case I wanted to mock a whole module and check if this was being called from the main function I was testing:

parent func(){  // The func my test was about
   childFunc() // The call I tried to mock and check if it was called.
...

, I tried using Sinon.spy(module, 'default') But kept throwing errors saying couldn't find 'default'. Seems stub, spy, and mock are all good when you want to mock results for function or you have functional properties. In my case switching to jest was super simple and achieved what I needed by just using

jest.mock('./module')

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