I am creating a middleware for making ajax requests using async actions. The middleware intercepts original action, performs ajax request, and re-dispatch
es the original action along with the response from the url
.
So, my Component would merely dispatch
an action like this
onClick() {
dispatch(ActionCreator.fetchUser());
}
Rest will be taken care by the middleware as shown here.
My question is, what should I do for unit testing? Should I mock the onClick
itself? or I should write a mocked middleware and forward the actions with the mocked response?
I am not sure which approach should I take. I tried several stuff, but none of what I tried made sense to me.
Any pointers?
Note: answer below is slightly outdated.
A much simpler updated approach is described here.
You can still do it the other way too, though.
We now have a section on testing async action creators in the official docs.
For async action creators using Redux Thunk or other middleware, it’s best to completely mock the Redux store for tests. You can still use
applyMiddleware()
with a mock store, as shown below. You can also use nock to mock the HTTP requests.can be tested like:
Turns out, I don't need to mock any store methods or anything. Its as simple as mocking the ajax request. I am using
superagent
, so I did it something like this