Jest.Mock vs Jest.SpyOn - What to use for Mocking

Jest

Sun Feb 05 2023

Introduction

There are a couple of ways that you can mock a function or method with Jest. However, there are implications based on which method you use. This post sets out to highlight the ways that you can mock within jest, the differences between them, and the pros and cons of each method. 

Introduction to Jest.Mock

The first way of mocking with Jest, and the most common, is using the jest.mock function to mock an entire file or package. 

Jest.Mock Pros

You can also make use of auto mocks with jest where if you see yourself repeating the same mocks for particular files then you can move that logic to a particular area and let jest auto mock it with the same implementation you have defined each time. 

Jest.Mock Cons

As mentioned this will mock the entire package or file which will result in all exported functions being mocked by default. Therefore, requiring additional set up if you wish to only mock a specific exported function. 

Mocking Individual Functions with Jest.Mock

However, this can be mitigated by making use of jest.mock function whilst re-requiring the mocked file with “requireActual” allowing you to mock specific exports regardless. 

When to use Jest.Mock

Overall Jest.Mock works best when wanting to mock entire files: which contain named or default exports or specific named or default exports of a file for the entire duration of the test. 

Introduction to Jest.SpyOn

Another way to mock within Jest is to make use of Jest.SpyOn function which lets you spy on specific exported functions or methods if mockImplementation is used. 

Jest.SpyOn Pros

You can easily state which method or function of a file you wish to mock when “mockImplementation” is used. Furthermore, if only part of your test requires a specific mock then it can easily be reset for the rest of the test suite. 

Jest.SpyOn Cons

By default Jest.SpyOn purpose is to listen and record what specific function or methods are doing. By default you are not mocking, instead your are just listening to the function or methods. Furthermore, when wanting to mock with Jest.SpyOn it is relatively difficult to mock a default export with Jest.SpyOn. 

When to use Jest.SpyOn

Jest.SpyOn works best when you want to conditionally mock an exported method or named function within your test suite. 

Conclusion

With Jest there are many ways to do the same thing. This post demonstrates the use cases , at a top level, of Jest.SpyOn vs Jest.Mock. There will always be ways to do the same thing with each but this post highlights what is relatively quick and easy to do with each method.