What is the difference between jest.fn() and jest.spyOn() methods in jest?

Pradhumn Sharma picture Pradhumn Sharma · Aug 25, 2019 · Viewed 14.4k times · Source

I am writing the Unit test cases for my react project and using jest and enzyme for writing test cases. I have read the jest documentation

https://jestjs.io/docs/en/jest-object.html#jestspyonobject-methodname

which explains about jest.spyOn() method but I didn't understand completely.

So I want to know more details about the specific places where we should use jest.fn() and Where we should/must use jest.spyOn(). It would be a great help if can be explained with an example for both methods.

Thanks

Answer

ysfaran picture ysfaran · Aug 25, 2019

My simple understanding of these two functions in react/frontend projects is the following:

jest.fn()

  • You want to mock a function and really don't care about the original implementation of that function
  • Often you just mock the return value
  • This is very helpful if you want to remove dependencies to the backend (e.g. when calling backend API) or third party libraries in your tests
  • It is also extremly helpful if you want to make real unit tests. You don't care about if certain function that gets called by the unit you test is working properly, because thats not part of it's responsibility.

jest.spyOn()

  • The original implementation of the function is relevant for your test, but:
    • You want to add your own implementation just for a specific scenario and then reset it again via mockRestore()
    • You just want to see if the function was called
    • ...
  • I think this is especially helpful for integration tests, but not only for them!

(Good blog post: https://medium.com/@rickhanlonii/understanding-jest-mocks-f0046c68e53c)