【发布时间】:2015-02-08 16:03:33
【问题描述】:
我正在使用 jasmine 作为测试框架,并且我有以下要测试的控制器。而且我总是有一个 Init() 函数,我可以在其中放置对该控制器的初始化调用。
现在我想测试初始化控制器时是否调用了 Init 函数。
function UnitTestsCtrl() {
var that = this;
this.Init();
}
UnitTestsCtrl.prototype.Init = function() {
var that = this;
//Some more Stuff
}
angular.module("unitTestsCtrl", [])
.controller("unitTestsCtrl", UnitTestsCtrl);
但我无法检查是否在创建控制器时调用了 Init 函数。我知道我的示例不起作用,因为间谍是在创建后在 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 函数中创建原始原型的间谍
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();
});
【问题讨论】:
标签: angularjs unit-testing jasmine