⚠️ This lesson is retired and might contain outdated information.

Inject dependencies into Epics

Shane Osbourne
InstructorShane Osbourne
Share this video with your friends

Social Share Links

Send Tweet

Often in unit tests we are focussing on the logic involved in crafting a network request, & how we respond to the result. The external service is unlikely to be under our control, so we need a way to ‘mock’ things like Ajax requests in a way that allows us to focus on the logic. In this lesson we’ll see how we can pass in dependencies into epics to make testing things Ajax requests easier.

Instructor: [00:00] The current implementation of this search feature makes some assumptions about the environment in which it's running. For example, we use this AJAX getJSON from RxJS AJAX. That assumes we're in an environment where that can even be run.

[00:20] Likewise, we're using this global variable document here, which again assumes we're in an environment that has the global variable document. Using these types of things within our epics make it harder to test and harder to reuse them in other environments.

[00:40] There's a simple solution, something that comes to us from the Redux-Observable library. They allow us to give a third argument here which is an object literal of dependencies that you can define.

[00:54] We can put getJSON here. We can remove this. This now would move into where we configure the store. As the only argument to create epic middleware, we give an object literal there and a special key, dependencies. We can give any number of items here.

[01:26] The reason we do this is that now this function is much, much easier to test, because it really is just a function that takes a stream of actions, a stream of state, and an object literal, in this case with just one function on it. We can also do this for things like the document.

[01:54] We would just move that to there. This tiny abstraction allows us to sell the store based on the environment. For example, we could have these as the default dependencies. Then we could spread in something that comes in here. We could set it to an empty object.

[02:18] Right now, in our application, we only have one place that uses this ConfigureStore function. That's in the index.js, where we're actually rendering to the DOM. By removing our dependencies away from the epics and into this object here, it means that in a test scenario, we can just call ConfigureStore, and we could pass in any of these to override them.

[02:41] Let's just verify everything still works. We can still search. Nothing's changed in the application, but we've just made it far, far easier to test in the future.