Jasmine说变量是未定义的,当它在函数中定义时

时间:2016-01-09 23:45:06

标签: angularjs jasmine karma-jasmine

这是我的sp.js

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

        var self = this;

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

这是我的test_sp.js

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

    beforeEach(function() {

        mockBaseService = {
            spls: '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', {
            });
        });


    });

     it('add() calls through to BaseService.add.sp.', function() {
         ctrl.sp = "{'spName': 'test post'}"
         spyOn(mockBaseService.add, 'sp');
         ctrl.add();
         expect(mockBaseService.add.sp).toHaveBeenCalledWith(ctrl.sp, jasmine.any(Function));
         expect(ctrl.cerrorMessages).toBe(mockBaseService.cerrorMessages);
     });   
});

当我通过karma start测试代码时,会引发此错误:

Expected undefined to be 'y'.
    at Object.<anonymous> (/home/a/Documents/CMS/CMSApp/static/js/karma/tests/test_sp.js:53:38)

并指向该行:

expect(ctrl.cerrorMessages).toBe(mockBaseService.cerrorMessages);

vome如何说ctrl.cerrorMessages未定义,即使在执行ctrl.add()之后,它在BaseService.add.sp()的回调中定义如下:

self.cerrorMessages = BaseService.cerrorMessages;

?我尝试在控制器的开头初始化变量,如下所示:

self.cerrorMessages;

但这也没有奏效(引发同样的错误)。

1 个答案:

答案 0 :(得分:2)

您可能希望通过调用来调用实际方法

spyOn(mockBaseService.add, 'sp').and.callThrough();