Inject the Dependencies

Dependency injection is a popular and common technique to replace a dependency with a test double. Rather than the code under test asking for its dependency, the dependency is injected—our industry likes fancy words—that is, passed in as an argument at the time of call. Let’s learn about this technique using the setLocation function as an example.

We discussed that the setLocation function should set the location property on a window object. What would otherwise be a very complex test to write turns out to be a simple test if we pass—ahem, inject—a stub for the window object. Let’s write the test for setLocation.

Let’s open the test/setlocation-test.js file in the locateme project in your workspace. To this ...

Get Test-Driving JavaScript Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.