Monkey patching
An alternative approach to dependency injection is monkey patching, where we dynamically modify the system at runtime. In our example, we might want to replace the create function with our stub functions, but only when we are running our tests.
Implementations of monkey patching libraries tend to be hacky and usually involves reading the module code into a string, injecting custom code into the string, and then loading it. Thus, the entities being monkey patched would be modified in some way.
There are several libraries that allow us to apply monkey patches when running tests; the most popular library is rewire (npmjs.com/package/rewire). It also has a Babel plugin equivalent called babel-plugin-rewire (github.com/speedskater/babel-plugin-rewire ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access