【发布时间】:2015-02-02 12:28:27
【问题描述】:
场景是我有一个ChildCtrl 控制器,它从BaseCtrl 继承this inheritance pattern:
angular.module('my-module', [])
.controller('BaseCtrl', function ($scope, frobnicate) {
console.log('BaseCtrl instantiated');
$scope.foo = frobnicate();
// do a bunch of stuff
})
.controller('ChildCtrl', function ($controller, $scope) {
$controller('BaseCtrl', {
$scope: $scope,
frobnicate: function () {
return 123;
}
});
});
假设BaseCtrl 做了很多事情并且已经过很好的测试,我想测试ChildCtrl 用某些参数实例化BaseCtrl。我最初的想法是这样的:
describe("ChildCtrl", function () {
var BaseCtrl;
beforeEach(module('my-module'));
beforeEach(module(function($provide) {
BaseCtrl = jasmine.createSpy();
$provide.value('BaseCtrl', BaseCtrl);
}));
it("inherits from BaseCtrl", inject(function ($controller, $rootScope) {
$controller('ChildCtrl', { $scope: $rootScope.$new() });
expect(BaseCtrl).toHaveBeenCalled();
}));
});
但是,当我运行测试时,从未调用过间谍,并且控制台显示“BaseCtrl 已实例化”,这表明 $controller 使用的是实际控制器,而不是我为 $provide.value() 提供的实例。
最好的测试方法是什么?
【问题讨论】:
标签: angularjs unit-testing inheritance jasmine