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.

5.1            Defining Isolation Frameworks

5.2            A quick look at the Isolation frameworks landscape

5.3            Choosing a loose vs typed “flavor”

5.4            Faking Modules Dynamically

5.4.1                     Some things to notice about jest’s API:

5.4.2                     Consider abstracting away direct dependencies

5.5            Functional Mocks and Stubs - Dynamically

5.6            Object Oriented Dynamic Mocks and Stubs

5.6.1                     Switching to a type-friendly Isolation Framework

5.7            Stubbing Behavior Dynamically

5.7.1                     An Object-Oriented example with a mock and a stub

5.7.2                     Stubs and Mocks with Substitute.JS

5.8            Advantages and traps of isolation frameworks

5.8.1                     You don’t need mock objects most of the time

5.8.2                     Unreadable test code

sitemap