2016-05-13 53 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