Mock Functions
Explore the different ways of mocking functions and how we can use them to increase confidence in our code.
We'll cover the following...
Why do we mock functions?
There are three main reasons that we mock functions in our tests.
- We have to. Sometimes we have no choice but to mock the calling of a function. For example, code that relies on a package connecting to an external service or authentication cannot run properly in our testing environment on its own. In this scenario, we have to mock the function so that our code can run.
- We want to control the function call or return value. If we are testing error handling, it may be easiest to cause the error by just telling Jest, “Have this function throw an error,” rather than creating the real-world behavior to throw the error. If we want to test that our logic works with the return value of a function as expected, it’s often easiest to do that by telling Jest, “Have this function return this value so that we know what we expect our code to do.” In both these situations, it is not the function being mocked that we are trying to test but rather how the rest of our code interacts with the running of the function. Gaining control over the function call and return value makes testing different scenarios massively easier.