0

Test:

it('call:start', function () {
  rootScope.$broadcast('call:start');
  expect(controller.conditionalPause.called).to.equal(true);
});

Passes:

$rootScope.$on('call:start', function () {
  self.conditionalPause();
});

Fails:

$rootScope.$on('call:start', self.conditionalPause);

Why?

In the failing test, it hits $on 'call:start and calls the callback. It even logs something out when I add a console.log to self.conditionalPause. So why isn't the test passing?

Adam Zerner
  • 17,797
  • 15
  • 90
  • 156
  • 1
    `self.conditionalPause.bind(self)` – elclanrs Mar 03 '16 at 01:48
  • Ah ok, thanks. Do you mind writing up the explanation as an answer? Also, any idea why I'm getting `undefined is not a function`, referring to `bind` when I run my Karma test? Is it overriding `Function.bind` or something? – Adam Zerner Mar 03 '16 at 01:55
  • It has to do with how `this` works. There are probably a bunch of duplicates for this particular case, but here is the most complete http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – elclanrs Mar 03 '16 at 01:56
  • I happen to know, but I figured it'd be useful to others who come across the question. It isn't immediately obvious that this is a `this` issue. At least not to me. I didn't find any dupes in searching, but maybe my queries were bad. – Adam Zerner Mar 03 '16 at 01:58
  • Regarding the bind issue with Karma, if you are using PhantomJS make sure it is at least version 2, otherwise you may have to include a polyfill. – elclanrs Mar 03 '16 at 01:59
  • 1
    I found another [detailed answer](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback), hope that helps. The key is understanding that `function(){return f()} === f` and `function(){return a.f()} === function(){return a.f.call(a)} === a.f.bind(a)` – elclanrs Mar 03 '16 at 02:09

0 Answers0