TAILIEUCHUNG - Test Driven JavaScript Development- P13

Test Driven JavaScript Development- P13:This book is about programming JavaScript for the real world, using the techniques and workflow suggested by Test-Driven Development. It is about gaining confidence in your code through test coverage, and gaining the ability to fearlessly refactor and organically evolve your code base. It is about writing modular and testable code. It is about writing JavaScript that works in a wide variety of environments and that doesn’t get in your user’s way. | Error Handling 233 By throwing an exception already when adding the observers we don t need to worry about invalid data later when we notify observers. Had we been programming by contract we could say that a precondition for the addObserver method is that the input must be callable. The postcondition is that the observer is added to the observable and is guaranteed to be called once the observable calls notifyObservers. The test fails so we shift our focus to getting the bar green again as quickly as possible. Unfortunately there is no way to fake the implementation this time throwing an exception on any call to addObserver will fail all the other tests. Luckily the implementation is fairly trivial as seen in Listing . Listing Throwing an exception when adding non-callable observers function addObserver observer if typeof observer function throw new TypeError observer is not function observer addObserver now checks that the observer is in fact a function before adding it to the list. Running the tests yields that sweet feeling of success All green. Misbehaving Observers The observable now guarantees that any observer added through addObserver is callable. Still notifyObservers may still fail horribly if an observer throws an exception. Listing shows a test that expects all the observers to be called even if one of them throws an exception. Listing Expecting notifyObservers to survive misbehaving observers test should notify all even when some fail function var observable new var observer1 function throw new Error Oops var observer2 function true observer1 observer2 assertTrue Please purchase PDF Split-Merge on to remove this watermark. From the Library of 234 The Observer Pattern Running the test reveals that the current implementation blows up along with