SpyOn returns 期待一个间谍,但得到了功能

SpyOn returns Expected a spy, but got Function

我正在测试调用服务(通过 goToPage 函数)以便使用 spyOn 进行重定向的控制器。这很简单,但我收到 "Expected a spy, but got Function." 错误。我究竟做错了什么? 这是我的规格:

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

});

首先,您在调用 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();
    });
});