2

我正在测试一个调用服务(通过 goToPage 函数)的控制器,以便使用 spyOn 进行重定向。这很简单,但我得到“预期是间谍,但得到了功能”。错误。我究竟做错了什么?这是我的规格:

var createController,service scope;
beforeEach(inject(function($rootScope, $controller,$injector){
    service = $injector.get('service ');
    scope = $rootScope.$new();
    createController = function() {
        return $controller('controller', {
            '$scope': scope
        });
        spyOn(service , ['redirect']).andCallThrough();
    };
}));

describe('test if service is called', function() {
    it('should call the service', function() {
        var controller=createController();
        scope.goToPage();
        expect(service.redirect).toHaveBeenCalled();
    });
});

});

4

1 回答 1

4

首先,您在调用 return 之后定义了您的间谍,这样代码将永远不会运行。其次,在您的测试中定义您的间谍,而不是在 beforeEach 中。

var createController,service scope;
beforeEach(inject(function($rootScope, $controller,$injector){
    service = $injector.get('service ');
    scope = $rootScope.$new();
    createController = function() {
        return $controller('controller', {
            '$scope': scope
        });    
    };
}));

describe('test if service is called', function() {
    it('should call the service', function() {
        var controller=createController();
        spyOn(service , ['redirect']).andCallThrough();
        scope.goToPage();
        expect(service.redirect).toHaveBeenCalled();
    });
});
于 2015-10-27T18:14:23.373 回答