Diogo Cardoso
Diogo Cardoso

Reputation: 22277

Spy on a function which is called by another function in Jasmine

How do I spy on a function which is called by another function in Jasmine?

The expectation is true if I call this.bar() but I'm not interested on that.

Spec

import * as src from './src;

describe('app', () => {
  it('should call bar', () => {
    spyOn(src, 'bar');
    src.foo();
    expect(src.bar).toHaveBeenCalled();
  });
});

Source

function foo() {
  bar();
}

function bar() {
  console.log('bar');
}

export {
  foo,
  bar,
};

Upvotes: 4

Views: 2781

Answers (2)

leobelizquierdo
leobelizquierdo

Reputation: 1668

Check this question: AngularJS - How to test if a function is called from within another function?. It seems that the function being tested (bar) needs to be call with the same reference as the function that is being spyOn (src.bar). You need to refer inside foo to src.bar, so you'll have to use this.bar.

Upvotes: 0

zangw
zangw

Reputation: 48536

In Jasmine, when you use spyOn, it mocks that function and doesn't execute anything. If you want to test further function calls within, you need to call and.callThrough() as below, please try it

spyOn(src, 'bar').and.callThrough();

Upvotes: 1

Related Questions