user1261710
user1261710

Reputation: 2639

Expected spies not being called on an inner function

I'm writing an app with AngularJS. I am writing unit tests for my angular service with karma and jasmine. It's not working as expected as the unit tests keep giving me these errors:

Expected spy photo to have been called.

Here is my codepen with the bug: https://codepen.io/aubz/pen/zXyvbj

Here is a code snippet of my unit test:

  it('should process the plain clocking settings', function () {

    ClockingRecordTypeFactory.getRecord('plain', 'here', null, null, null, null, null);

    spyOn(ClockingRecordTypeFactory, 'plain').and.callFake(function () {});
    spyOn(ClockingRecordTypeFactory, 'photo').and.callFake(function () {});
    spyOn(ClockingRecordTypeFactory, 'geo').and.callFake(function () {});
    spyOn(ClockingRecordTypeFactory, 'manual').and.callFake(function () {});

    expect(ClockingRecordTypeFactory.plain).toHaveBeenCalled();
    expect(ClockingRecordTypeFactory.photo).not.toHaveBeenCalled();
    expect(ClockingRecordTypeFactory.geo).not.toHaveBeenCalled();
    expect(ClockingRecordTypeFactory.manual).not.toHaveBeenCalled();

});

and of the function I am trying to test:

function getRecord(type, origin, coords, imageData, comments, reason, date) {

    var record = getBaseClockingRecord();

    if (type === 'plain') {
        plain(record);
    }

    if (type === 'photo') {
        photo(record);
    }

    if (type === 'geo') {
        geo(record, coords);
    }

    if (type === 'manual') {
        manual(record);
    }

    return record;
}

Upvotes: 1

Views: 38

Answers (1)

sheilak
sheilak

Reputation: 5873

The test is spying on ClockingRecordTypeFactory.plain but actually the getRecord function calls the local function plain so the spy will not be called at all.

You can make the spies work as intended by changing getRecord like this:

if (type === 'plain') {
    this.plain(record);
}

if (type === 'photo') {
    this.photo(record);
}

if (type === 'geo') {
    this.geo(record, coords);
}

if (type === 'manual') {
    this.manual(record);
}

Also you need to set up your spies at the start of the test before calling getRecord:

spyOn(ClockingRecordTypeFactory, 'plain').and.callFake(function () {});
spyOn(ClockingRecordTypeFactory, 'photo').and.callFake(function () {});
spyOn(ClockingRecordTypeFactory, 'geo').and.callFake(function () {});
spyOn(ClockingRecordTypeFactory, 'manual').and.callFake(function () {});

ClockingRecordTypeFactory.getRecord('plain', 'here', null, null, null, null, null);

Updated Codepen

Upvotes: 1

Related Questions