2016-05-13 50 views
0

我已经看到一组重复的问题,但无法解决问题。Jasmine Js - SpyOn Fakecall在控制器初始化期间

我有一个控制器,并在控制器初始化期间,fetchtemplate()先被调用,然后我的模拟fetchtemplate()被调用。

如何在控制器初始化期间停止调用实际(控制器)fetchtemplate()?我的本意是嘲笑功能fetchtemplate()在我的spec.Please看看我的规格 -

describe("...",function(){ 
    beforeEach(inject(function($controller,...) { 
    scope  = $rootScope.$new(); 

    this.init = function() { 
        $controller('ChangeControlCreateController', { 
        $scope: scope 
        }); 
       } 
    })); 
    describe('Function', function() { 

     it("-- check for trueness",function(){ 

     this.init()  ; //Initialization of the controller 
     spyOn(scope,'fetchtemplate').and.callFake(function() { 
        return 101; 
       }); 
     var fakeResponse = scope.fetchtemplate(); 
     expect(scope.fetchtemplate).toHaveBeenCalled(); 
     expect(fakeResponse).toEqual(101);  
     }); 


    }); 
}); 

我试图放置spyOn这给了错误的fetchtemplate()在不存在this.init()前时间间谍。

我的控制器代码结构看起来像 -

angular.module('...', [...]) 

    .controller('ChangeControlCreateController', ["$scope"..., 
    function ChangeControlCreateController($scope,...) { 
     $scope.fetchtemplate = function() { 
      console.log("controller's function");    
      ... 
     }; 
     $scope.fetchtemplate(); 
    }); 

我所得到的结果是 - 首先控制台项目“控制器的功能”,然后规范与模拟功能的执行。我想模拟功能执行没有控制器的功能执行

+0

你可以给我们的控制器代码吗?我需要看看你如何调用fetchtemplate方法 – sam

+0

当然,我也添加了控制器代码结构。 @sam – M3ghana

回答

1

因此,如果我理解正确,你正在做一些功能,你正在做的事情,你想防止测试目的。可能是一个http调用或类似的东西?

无论它在做什么,处理这种事情的正确方法通常是将该方法放在服务中,然后监视该服务方法。下面是该服务是否TemplateService测试的例子:

describe("...",function(){ 

var $controller, scope, TemplateService, YourController; 

beforeEach(inject(function(_$controller_, _TemplateService_, ...) { 
    scope = $rootScope.$new(); 
    $controller = _$controller_; 
    TemplateService = _TemplateService_; 
} 

it("-- check for trueness",function(){ 

    spyOn(TemplateService,'fetchTemplate').and.returnValue('101'); 

YourController = $controller('YourController'); 
    expect(...); 
}); 


}); 

我希望这是有益的

+0

嗨,山姆,谢谢你的回复。我可以解决这个问题,而无需将我的功能放入服务中吗? – M3ghana

+0

你可能可以通过覆盖角度基本行为或者通过某种我从未发现的方式。正如你所说,你不能介入一些还不存在的东西 – sam

+0

好的,谢谢。 – M3ghana