Unit tests for callback-driven flow in CS
If you synchronize your frontend with backend you probably use some AJAX, maybe through jQuery or something else. It pushes you to use callbacks, which are hard to test, especially if they are anonymous functions. Other option is to use short callbacks with event triggering, but it feels like overkill in case, when you want to use it once per runtime.
In our project we decided to use callback for such communication, via ServerSide object. We also extracted usecases, simple classes that describes communication algorithms between domain models, server-side and some other, like FB JS SDK. Each usecase gets its dependecies in constructor and can start with execute method. This execute method accepts some parameters and sometimes we need to pass them to, invoked by ServerSide, callback. How to get this work?
As you can see stubing ServerSide is really easy, but how can we check if doSmthWith was called with params we want? In Jasmine it is also easy:
You see – no rocket science here. But what if parameters are more complicated, so we can’t use toHaveBeenCalledWith? I mean – there is some callback passed, or other not-so-easy-to-compare thing? First of all – you probably have design problem – rethink your problem and find easier way to express it. Ok, but we can think about situation, when we only want to check, if first and third parameter have some value, and other aren’t interesting for us. Here’s how we do that: