Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Jest Mock functions and Sinon spies

Tags:

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

like image 797
Special Character Avatar asked Feb 16 '17 20:02

Special Character


People also ask

What is difference between mock and spy jest?

Both can be used to mock methods or fields. The difference is that in mock, you are creating a complete mock or fake object while in spy, there is the real object and you just spying or stubbing specific methods of it. When using mock objects, the default behavior of the method when not stub is do nothing.

What is a jest mock function?

Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new , and allowing test-time configuration of return values.

What does Sinon spy do?

The function sinon. spy returns a Spy object, which can be called like a function, but also contains properties with information on any calls made to it. In the example above, the firstCall property has information about the first call, such as firstCall. args which is the list of arguments passed.

How do you mock a function in Sinon?

Mocks allow you to create a fake function that passes or fails depending on your needs. You can ensure it was called with certain arguments, or check how many times it was called. You must call mock() on an object.


1 Answers

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.

like image 110
Andreas Köberle Avatar answered Oct 22 '22 21:10

Andreas Köberle