To Mock or Not to Mock, That is The Question

Chak Shun Yu
4 min readMay 28, 2021

Mocking dependencies of your code is one of the fundamental aspects of software testing. It’s a powerful method that allows developers to gain control over a certain part of your code and create an isolated environment for your test if done too much. This will make your tests less reliable and create a false sense of security, which is exactly not what we want.

The key is to be thoughtful of what you’re mocking and for what reason you’re mocking it. If you’re e.g. mocking child components in React tests just because they’re annoying, you’re actively diminishing the representativeness of your tests. This is exactly not what we want. To help you with mocking, this article will share three tips for when it makes sense to mock and how to approach mocking in your tests.

Mock Code That Is Irrelevant and Resource Heavy

If running a piece of code is not related to how the users interact with it but do require quite some overhead, it’s a perfect candidate for mocking it away. Something like expensive calculations in the background or loading an entire sidebar is not relevant for when you’re verifying whether something is working properly on the main screen.

The most important question to ask yourself is whether the code you are mocking influences the representability of your tests. If not, then mocking is perfectly fine. But if it does, then you shouldn’t mock it even if it introduced a (significant) overhead in your tests. This differs per test suite or even test case as it depends on the relationships between pieces of code in your codebase. Therefore this should be analysed on a test-by-test basis.

Mock Code That Is Relevant and You Want Control Over

The next scenario is when the code does (directly) affect the results of your tests, but you want control over the different scenarios that it causes to verify them. This can be code that interacts with external APIs, data fetching, props, and so on. If you want to verify different flows of your application or component based on whether e.g. errors happen or not, then you want it to be deterministic across CI test runs and not flake every other time.

--

--

Chak Shun Yu

Lifelong learner working as a frontend engineer. React. Self Development and Reflection. Testing. Technical Blogging.