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

Simulate network errors within tests

Shane Osbourne
InstructorShane Osbourne
Share this video with your friends

Social Share Links

Send Tweet

Handling errors correctly in an application can be one of the most important parts of any project - it’s crucial to get it right and therefor it warrants having unit tests covering it. Again, because we’re using the power of Rx, this is an extremely straightforward task.

Instructor: [00:00] We have a test here for an application, but it's really only exercising a single happy path. We are stubbing the getJSON method and returning a simple piece of data. If we look inside the epic, that means that this part always returns some data, which means we'll end up here. We never, ever get inside this catchError.

[00:25] It's extremely important that this catchError function exists. Should an error message occur, we need to ensure that we catch that error so that we can show a nice message to the user. Let's return an empty observable here, just to prove that our test will still pass. If an error did occur inside the application now, the user would never know about it.

[00:50] Let's write a test to handle this case. Let's rename this one to say that this handles the success case. We're just going to copy/paste for now. Of course, you can abstract this into some test helpers if you'd like. We're going to deal with the error case.

[01:14] It says we have two passed, two in total. The action will stay the same. The state stays the same. The thing we're going to change here is that we're not going to produce an element here. We are instead going to throw an error. The way we do that is we give a hash sign. We remove the values. We can just give that as null. The third argument here will be the value of the error.

[01:48] We happen to know that should the AJAX request produce an error, it'll have a response key. We know that the API we're dealing with has a message. We can just say, "Oops." That will simulate an error in this getJSON method.

[02:15] We should assert what we expect. We would still expect to go into a pending state first. Here, we would expect a failure. We'll import the fetch failed action creator. Looking at its signature, we just send through a message. It's going to be the same message as this.

[02:43] That's what we expect. We still get the failure here, just how we wanted it to be. This failure in particular is showing us that we only have one item produced. We expected two. Go back to our epic and undo that. Now you can see it passes.