5 Isolation (mocking) frameworks
This chapter covers
- Defining isolation frameworks and how they help
- Two main “flavors” of frameworks
- Faking modules with jest
- Faking functions with jest
- Object Oriented Fakes with Substitute
In the previous chapters, we looked at writing mocks and stubs manually and saw the challenges involved, especially when the interface we’d like to fake requires us to create long manual and error prone repetitive code.
We kept having to declare custom variables, create custom functions or inherit from classes that use those variables and basically make things a bit more complicated that they need to be (most of the time).
In this chapter, we’ll look at some elegant solutions for these problems in the form of an isolation framework—a reusable library that can create and configure fake objects at runtime. These objects are referred to as dynamic stubs and dynamic mocks.
I call them isolation frameworks because they allow you to isolate the unit of work from its dependencies. You’ll find that many resources will refer to them as “mocking frameworks”. I try to avoid calling them mocking frameworks because they can be used for both mocks and stubs. We’ll take a closer look at a few of the JavaScript frameworks available and how we can use them in modular, functional and object-oriented designs. You’ll see how you can use such a framework to test various things and to create stubs, mocks, and other interesting things.