Thursday, May 5, 2016

Smarter Spying in Jasmine

While I was testing some Angular code today I came across a section that was a bit difficult to test.  There's a try/catch block where the try calls a function (numeral.language) and then the catch calls the same block.  The issue with testing was that if I spied on numeral.language and used .and.throwError() the function would throw an error both times and my test would 'splode.  The workaround turned out to be pretty straightforward.


var callCount;
beforeEach(function() {
  callCount = 0;
  spyOn(numeral, 'language').and.callFake(function() {
    if (callCount === 0) {
      callCount++;
      throw new Error('Unknown language');
    }
  });
});

The first time through the method (when callCount is 0), manually throw an error (instead of using .and.throwError()) and increment callCount.  The next time the fake gets called, it won't throw an exception.  I'm still working on how to call through to the original method after that, but I don't need it right now and I didn't want to forget this.

No comments:

Post a Comment