Jasmine 间谍未跟踪在页面加载时执行的 JS 函数

JS function which executes on page load not being tracked by Jasmine spy

这是我的 test_sp.js:

describe('Controller: MainCtrl', function() {
    var ctrl, mockBaseService;

    beforeEach(function() {

        mockBaseService = {
            sps: 'x',
            cerrorMessages: 'y',
            add: { sp: function(something, cb) { cb() } },
            fetch: { selfsps: function(cb) { cb() } },
            logout: function() {},
        };


        module('BaseApp', function($provide) {
            $provide.value('BaseService', mockBaseService);
        });

        module('SpPageApp');


        inject(function($controller) {
            ctrl = $controller('MainCtrl', {
            });
        });

        spyOn(mockBaseService.fetch, 'selfsps');

    });

     it('should fetch sps from BaseService.fetch.selfsps right away.', function() {
         expect(mockBaseService.fetch.selfsps).toHaveBeenCalled();
     });

});

这是我的 sp.js:

angular.module("SpPageApp", ["BaseApp"])
    .controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) {

        var self = this;

        // Call BaseService.fetch.selfsps at the beginning of the file.
        BaseService.fetch.selfsps(function() {
            self.sps = BaseService.sps;
            self.cerrorMessages = BaseService.cerrorMessages;
        });

        self.add = function() {
            BaseService.add.sp(self.sp, function() {
                self.cerrorMessages = BaseService.cerrorMessages;
            });
        };    
    }]);

BaseServicebase.js 中的 BaseApp 模块中。

话虽如此,当我通过 karma start 测试代码时,我得到了这个错误:

    Expected spy selfsps to have been called.
        at Object.<anonymous> (/home/a/Documents/CMS/CMSApp/static/js/karma/tests/test_sp.js:59:56)
Chromium 47.0.2526 (Ubuntu 0.0.0): Executed 5 of 5 (1 FAILED) (0 secs / 0.105 secChromium 47.0.2526 (Ubuntu 0.0.0): Executed 5 of 5 (1 FAILED) (0.15 secs / 0.105 secs)

并指向这一行:

expect(mockBaseService.fetch.selfsps).toHaveBeenCalled();

为什么 mockBaseService.fetch.selfsps 没有被调用,即使在我的 sp.js 中,我在文件的开头调用它?

您首先要实例化控制器。这调用了 BaseService.fetch.selfsps() 函数。然后,您才开始监视该功能。太晚了。

您需要在实例化控制器之前进行监视。就像,如果你想监视 phone 对话,你需要在对话开始之前开始收听。如果您在对话结束后开始收听,您将听不到任何声音。