Woah what a title….
So every now (almost always) and then you’ll come across the need for an action creator that does something async, perhaps making an API request using axios, which in turn opens up redux-thunk as a middleware tool to deal with making these sorts of requests and dispatching actions based on the response.But testing these can get a bit messy. Here’s one solution.
Learning by example
- I have a server, which exposes a Signup API endpoint
- My client app (a React/Redux app), contains a form that collects this data
- OnSubmit it dispatches this data to an action creator called signUpUser
- This function in turn executes an axios promise to our authentication endpoint.
- It function takes in an email, and a password and on success returns a JWT token
- We will dispatch AUTH_USER and save the JWT token returned in localstorage on success
- We will dispatch AUTH_ERROR if the response returned is an error
So let’s assume you’ve got a component with a form up and running and doing it’s thing. Our action might look something like this:
And now let’s import this action to our index.js file for a centralized point of contact for our tests. It’s kinda superficial for this post but once things grow, you’ll see why it’s important.
And just for the sake of newcomers, our reducer might looks something like this:
Similarly let’s combine our reducers
Now how do we test this asyn’d stuff?
Well let’s lay it out, we’ll need:
- A test runner. I’ll use Mocha
- An assertion library. I’ll use Chai
- Some way to stub LocalStorage since our action is setting localStorage, I’ll do it myself, but npm probably has you covered.
- Some way to stub the Axios calls, I’ll use moxios.
- We’ll need to import our thunk middleware to mock expected actions
Mocking Local Storage
Now in this example we’ll need the worlds tiniest mock of localStorage but we can basically just create a function that returns the duplicated internal methods localStorage has available. In this case we’ll only need access to setItem (you can read more about localStorage here), but for a fully fleshed out action creator test suite you’ll probably need to also test a few other methods associated with localStorage. So here’s something to get you started.
Now testing an action creator isn’t too diffcult since :
In Redux, action creators are functions which return plain objects. When testing action creators we want to test whether the correct action creator was called and also whether the right action was returned.
Simply put we give it a type & data, and we expect the action that was called to have the same type and a specific payload. So let’s setup our test.
And that’s one way to go about it!
Thanks for reading!
And if you see anything wrong, or that could be better, let me know! We’re all learning!