Mocking an ajax request when testing epics

Shane Osbourne
InstructorShane Osbourne

Share this video with your friends

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’ the Ajax request 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.
~ 4 years ago

I think the current methods for testing isn't great.

  1. You need to make significant changes to the epic code - the example given added parameters to the epic but more changes were made to this code before the lesson started when compared to previous lessons - the following function was defined outside of the epic in earlier lessons but in this lesson it is inside the epic. const ajax = term => Observable.ajax.getJSON(search(term))

  2. You need to change code when setting up epic middleware

I don't think the idea of changing code to suit a test is good practice

Philip Cox
Philip Cox
~ 3 years ago

Hi. I've been following along, and it all seems to be working, accept my test only receives one ACTION rather than two.

{ type: 'SEARCHED_BEERS_LOADING', payload: true }

But I don't get

{ type: RECEIVED_BEERS, payload: beers }

When I should.

Also, .toArray() on the subscribe is not working for me??


Victor Eloy
Victor Eloy
~ 2 years ago

What happens at 6:32 in your video shows exactly why isn't a good idea to change your function to fit the test. Basically you are forcing your method to adapt to your tests and by doing so you are generating a false positive as your test pass but still will not work in production because you are sending the wrong object.