jds
jds

Reputation: 8259

Why does this Jasmine spy cause an error?

I have some code:

var bar = function() { ... };
var foo = function() { bar(); };

And a Jasmine test:

describe('foo', function() {
    it('calls bar', function() {
        spyOn(window, 'foo'); // this line causes an error
        spyOn(window, 'bar');
        foo();
        expect(bar).toHaveBeenCalled();
    });
});

The commented line causes this error:

Expected spy bar to have been called.

Does Jasmine spying on foo somehow kill its native implementation? If I remove the commented line, the test passes.

Upvotes: 2

Views: 700

Answers (2)

raina77ow
raina77ow

Reputation: 106385

The purpose of this particular test to check whether or not invocation of foo() results in invocation of bar(). For the purpose, that...

it('calls bar', function() {
  spyOn(window, 'bar');
  foo();
  expect(bar).toHaveBeenCalled();
});

... is sufficient. Yes, you have to mock bar function, so instead of doing its job it'll just report about its call. But in no way you should mock foo with spyOn - you're testing the function, not the mock!

And if, for some reason, you just ought to have it observed, use andCallThrough spy method:

it('calls bar', function() {
  spyOn(window, 'foo').andCallThrough();
  spyOn(window, 'bar');
  foo();
  expect(bar).toHaveBeenCalled();
});

This way the mock will still be created (so you can use some of its methods - checking how many times the function is called, for example); the difference is calling the original function foo at the end of the mock's job.

Upvotes: 5

Brett Shwom
Brett Shwom

Reputation: 1

spyOn(window, 'foo').andCallThrough()

Upvotes: 0

Related Questions