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 file, we’ll ...
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