5 Isolation 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.js

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, 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 than they need to be (most of the time).

In this chapter, we’ll look at some elegant solutions to these problems in the form of an isolation framework—a reusable library that can create and configure fake objects at run time. 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,” but I try to avoid that because they can be used for both mocks and stubs. In this chapter, we’ll take a 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 frameworks to test various things and to create stubs, mocks, and other interesting things.

5.1 Defining isolation frameworks

5.1.1 Choosing a flavor: Loose vs. typed

5.2 Faking modules dynamically

5.2.1 Some things to notice about Jest’s API

5.2.2 Consider abstracting away direct dependencies

5.3 Functional dynamic mocks and stubs

5.4 Object-oriented dynamic mocks and stubs

5.4.1 Using a loosely typed framework

5.4.2 Switching to a type-friendly framework

5.5 Stubbing behavior dynamically

5.5.1 An object-oriented example with a mock and a stub

5.5.2 Stubs and mocks with substitute.js

sitemap