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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With