如何窥探在Jasmine beforeEach代码块中创建的函数?

时间:2016-02-22 01:21:50

标签: angularjs jasmine karma-jasmine

这是我的代码:

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();
    });
});

当我运行此测试时,我收到错误消息:

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

并指向行spyOn('cb')。监视beforeEach代码块中创建的函数的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

你只能监视一个对象,这就是为什么spyOn的语法是:

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

spyOn(objFoo, 'funcBar');

因此,创建一个包含函数的对象。

或间谍窗口,看到你将 cb 视为全局变种:

spyOn(window, 'cb');

虽然不是真的推荐: - )

答案 1 :(得分:1)

通常,应使用spyOn来删除依赖项 - 对我来说,监视测试本身定义的函数似乎很奇怪。

在这种情况下,我可能只是创建一个间谍并直接将其传递给BaseService.logout

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();
});