在Jasmine间谍

时间:2016-01-09 22:34:53

标签: angularjs jasmine karma-jasmine

这是我的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;
            });
        };    
    }]);

BaseService位于BaseApp的{​​{1}}模块中。

话虽如此,当我通过base.js测试代码时,我收到此错误:

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中,我在文件的开头调用它?

1 个答案:

答案 0 :(得分:1)

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

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