Introduction to Mocking Packages

Learn why and how we mock dependencies.

Why do we mock packages?

Open-source software is a vital part of any modern codebase. It allows us to gain robust features and support complex logic with as little as just a few lines of code. These same external libraries often don’t play nice with testing environments out of the box, though.

This won’t be true for all external packages, and each package should be considered individually. Entire frameworks like Koa and Angular are packaged as third-party code, and we don’t want to mock these. Additionally, some libraries might provide functionality that just doesn’t need to be mocked, such as the format or joi packages.

Mocking our external packages can feel overwhelming at first. Often when we start running our tests, if we haven’t mocked a package, the errors we find ourselves facing can feel out of place, unhelpful, and difficult to debug. This is because the code, and therefore the error handling, is intended to be running in a real-world environment, not a test environment. Therefore, it can be confusing to discern what’s happening.

How do we mock packages?

Mocking all packages comes down to a singular guiding philosophy. Mocking dependencies is about creating an object that matches the interface of the package being mocked. What do we mean when we say “matches the interface”?

Get hands-on with 1200+ tech skills courses.