【发布时间】:2016-09-09 11:49:25
【问题描述】:
我看到了这个问题的一组重复项,但无法解决问题。
我有一个控制器,在控制器初始化期间,首先调用 fetchtemplate(),然后调用我的模拟 fetchtemplate()。
如何在控制器初始化期间停止调用实际的(控制器)fetchtemplate()?我的意图是在我的规范中模拟函数 fetchtemplate()。请看一下我的规范 -
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 放在 this.init() 之前,这会导致错误,因为当时不存在 fetchtemplate() 来进行 spyOn。
我的控制器代码结构看起来像 -
angular.module('...', [...])
.controller('ChangeControlCreateController', ["$scope"...,
function ChangeControlCreateController($scope,...) {
$scope.fetchtemplate = function() {
console.log("controller's function");
...
};
$scope.fetchtemplate();
});
我得到的结果是 - 首先是控制台项“控制器的功能”,然后是使用模拟功能执行规范。我希望模拟函数执行没有控制器的函数来执行
【问题讨论】:
-
您也可以给我们控制器代码吗?我需要看看你是怎么调用那个 fetchtemplate 方法的
-
当然,我也添加了控制器代码结构。 @山姆
标签: angularjs unit-testing jasmine karma-jasmine spyon