Testing mocked module methods with Jest
Recently I started a playground project to use React, Redux and some SDK to connect with an existing API.
After learning how to test components with
enzyme (thanks again, Airbnb), I went for Redux Actions including async methods using
redux-thunk. Most of the examples I was able to find were using examples of modern JS approaches, like using
fetch methods directly in the actions. However, even if I could try to follow that approach, my project required a different way.
Let’s consider a classic JS SDK called
old-module-sdk that inits with a JS object constructor and provides an API with methods that, instead of promises, they follow a error-first callback approach.
First of all, what I did is to wrap the module in a ES6 module to be imported after init and reused across the code:
This will allow me to set any kind of requirements the SDK could have, such as Auth Tokens.
So, how does our actions file that uses this look like? Here we go. It should have an async action to getData, plus some different actions to show the status of the loading (that can be used to show loading indicators and that kind of stuff, you know what I mean ;)
We wrap our
getDataMethod to follow the same pattern as modern examples with
fetch and try to use the promise response in our tests. As you can see, the process is:
- Dispatch a start fetching action before the call starts.
- Perform the call.
- Stop fetching data.
- Dispatch the success or error actions.
- Close the promise.
Ok, we have our actions. Now our tests:
Basically the secret sauce here is to use the Jest method
mockImplementation over the imported
getDataMethod after it’s owner
OldModuleApi was also mocked. Using
redux-mock-store we can create a false store to keep control of the actions dispatched.
And that’s it :)