I gave a course recently on unit testing in Angular, and we were looking at some code the developers wrote, and we wanted to test.

It looked something like this:

someApiCallAsync(p1, p2, ...)
.then(response => {
    if (response.ok){
    ....
    }
    else {
    .....
    };
})

Basically we’re looking at an async API call, and after it completes, we check the response and do something with it. The code uses the Promise construct in JavaScript, which is basically async / await in other languages.

The discussion went in the direction of “how do we mock the API so it returns the status and body we want asynchronously”.

Well, it’s easy to do with Jasmine spies. But is it necessary?

What we really want to check is the behavior of the code after the async call was mad, which is in the then() block. The mocking is just a technique to get there.

Instead, we can extract what’s inside the then() block to another method and test that one, without any mocking. Like this:

function checkResponse(response => {
  if (response.ok){
  ....
  }
  else {
  .....
  };
});

Now we don’t need to mock anything, just check a simple function.

Sometimes we need to remember what we want to check, rather than just go ahead using the mock gun. It can easily be done by simpler means.

These are the things that I focus in my courses. Actual, useful, simple techniques to help you code and test better.  And on the code you write! If you’re interested a course, contact me!

Categories: Uncategorized

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *