SilentDev
SilentDev

Reputation: 22747

How to spyOn a function created inside the Jasmine beforeEach block of code?

This is my code:

describe('Factory: BaseService', function() {
    var fctry, mockBackend;

    beforeEach(function() {

        module('BaseApp');

        cb = function() {};

        inject(function(_BaseService_, _$httpBackend_) {
            mockBackend = _$httpBackend_;
            BaseService = _BaseService_;
        });
    });

    it('logout() should POST to /logout', function() {
        spyOn(BaseService, 'accessErrors').and.callThrough();
        spyOn('cb');
        mockBackend.expectPOST("/logout").respond(404, {msg: 'Not Found'});

        BaseService.logout(cb);

        mockBackend.flush();

        expect(BaseService.accessErrors).toHaveBeenCalled();
        expect(BaseService.cerrorMessages).toEqual(['Not Found']);
        expect(cb).toHaveBeenCalled();
    });
});

When I run this test, I get an error which says:

Chromium 48.0.2564 (Ubuntu 0.0.0) Factory: BaseService logout() should POST to /logout FAILED
    Error: No method name supplied

and it points to the line spyOn('cb'). What is the correct way to spy on a function created in the beforeEach block of code?

Upvotes: 2

Views: 1328

Answers (2)

mgilson
mgilson

Reputation: 309929

Usually, spyOn should be used to remove a dependency -- It seems weird to me to spy on a function that is defined in the test itself.

In this case, I might just create a spy and pass it to BaseService.logout directly:

it('logout() should POST to /logout', function() {
    spyOn(BaseService, 'accessErrors').and.callThrough();

    // just create the spy here -- no need to create a function so you can replace
    // it with a spy via spyOn :-).
    var cb = jasmine.createSpy('cb');

    mockBackend.expectPOST("/logout").respond(404, {msg: 'Not Found'});

    BaseService.logout(cb);

    mockBackend.flush();

    expect(BaseService.accessErrors).toHaveBeenCalled();
    expect(BaseService.cerrorMessages).toEqual(['Not Found']);
    expect(cb).toHaveBeenCalled();
});

Upvotes: 1

andyhasit
andyhasit

Reputation: 15289

You can only spy on an object, which is why the syntax for spyOn is:

objFoo = {};
objFoo.funcBar = function() {};

spyOn(objFoo, 'funcBar');

So create an object to contain your function.

Or spy on window, seeing as you made cb a global var:

spyOn(window, 'cb');

Though that's not really recommended :-)

Upvotes: 1

Related Questions