我使用 jasmine 作为测试框架,并且我有以下要测试的 Controller 。我总是有一个 Init() 函数,我可以在其中对此 Controller 进行初始化调用。
现在我想测试 Controller 初始化时是否调用了 Init 函数。
function UnitTestsCtrl() {
var that = this;
this.Init();
}
UnitTestsCtrl.prototype.Init = function() {
var that = this;
//Some more Stuff
}
angular.module("unitTestsCtrl", [])
.controller("unitTestsCtrl", UnitTestsCtrl);
但是我无法检查在创建 Controller 时是否调用了 Init 函数。我知道我的示例不起作用,因为 spy 是在创建后在 Init 函数上设置的。
describe('Tests Controller: "UnitTestsCtrl"', function() {
var ctrl;
beforeEach(function() {
module('app.main');
inject(function ($controller) {
ctrl = $controller('unitTestsCtrl', {});
});
});
it('Init was called on Controller initialize', function () {
//thats not working
spyOn(ctrl, 'Init');
expect(ctrl.Init).toHaveBeenCalled();
});
});
解决方案:
在 beforeEach 函数中创建原始原型(prototype)的 spy
beforeEach(function() {
module('app.main');
spyOn(UnitTestsCtrl.prototype, 'Init');
inject(function ($controller) {
ctrl = $controller('unitTestsCtrl', {});
});
});
it('Init was called on Controller initialize', function () {
expect(ctrl.Init).toHaveBeenCalled();
});
最佳答案
事情就是这样,你不能也确实不需要。不能的原因是因为您在 Controller 构造函数上调用 init()
,即在实例化时,当您调用 $controller
服务在测试中实例化 Controller 时会发生这种情况。所以你设置 spy 为时已晚。您可能不需要,因为如果实例化 Controller ,则肯定会调用 init 方法。但是,如果您在 init 内进行任何特定的服务/依赖项调用,您就可以监视这些模拟并设置期望。
您的期望是:已执行服务调用
,因此为该服务创建一个 spy 并设置期望。
示例:
var myService = jasmine.createSpyObj('myService', ['someCall']);
myService.someCall.and.returnValue($q.when(someObj));
//...
ctrl = $controller('unitTestsCtrl', {'myService':myService});
并设置对 myService 的 someCall 方法的期望。
expect(myService.someCall).toHaveBeenCalled();
如果您确实想监视 init
,那么您需要有权访问规范中的 UnitTestsCtrl
构造函数,并且需要在其原型(prototype)方法上设置监视实例化之前的init
。
关于AngularJs 单元测试 - 检查 "Init"函数是否被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28396107/