我有一个像下面的控制器
(function () {
angular.module("WatchApp", [])
.controller("WatchController", function ($scope) {
$scope.options = {
rowSelection: true
, multiSelect: false
, autoSelect: false
, decapitate: false
, largeEditDialog: false
, boundaryLinks: false
, limitSelect: true
, pageSelect: true
};
$scope.$watch($scope.options.rowSelection, function (newValue, oldValue) {
if (!oldValue) {
console.log("! old Value ");
}
if (newValue !== oldValue) {
console.log("newValue != old Value ");
}
if (!newValue) {
console.log("! newValue");
}
});
});
}());
我也有这个控制器的UT,如下所示
describe("WatchController", function () {
var $scope;
beforeEach(function () {
module("WatchApp");
return null;
});
beforeEach(
inject(function (_$controller_) {
$scope = {};
controller: _$controller_("WatchController", {
$scope: $scope
});
}));
describe("Initialization", function () {
it("newPlace.city and country should be empty", function () {
expect($scope.options.rowSelection).toEqual(true);
})
});
});
如果我删除$ scope。$ watch块,这个UT工作正常,否则我得到以下异常。
PhantomJS 2.1.1 (Windows 7 0.0.0) WatchController Initialization newPlace.city and country should be empty F
TypeError: undefined is not a constructor (evaluating '$scope.$watch') (line 15)
C:/Robin/Studies/Angularjs/ut/app/controllers/watchController.js:15:26
[native code]
instantiate@C:/Robin/Studies/Angularjs/ut/bower_components/angular/angular.js:4680:61
$controller@C:/Robin/Studies/Angularjs/ut/bower_components/angular/angular.js:10130:39
C:/Robin/Studies/Angularjs/ut/bower_components/angular-mocks/angular-mocks.js:2194:21
C:/Robin/Studies/Angularjs/ut/test/controllers/watchControllerSpec.js:10:38
invoke@C:/Robin/Studies/Angularjs/ut/bower_components/angular/angular.js:4665:24
workFn@C:/Robin/Studies/Angularjs/ut/bower_components/angular-mocks/angular-mocks.js:2965:26
inject@C:/Robin/Studies/Angularjs/ut/bower_components/angular-mocks/angular-mocks.js:2931:28
C:/Robin/Studies/Angularjs/ut/test/controllers/watchControllerSpec.js:8:15
global code@C:/Robin/Studies/Angularjs/ut/test/controllers/watchControllerSpec.js:1:9
PhantomJS 2.1.1 (Windows 7 0.0.0): Executed 14 of 14 (1 FAILED) (0.016 secs / 0.39 secs)
答案 0 :(得分:0)
将监视行代码更新为:
$scope.$watch('options.rowSelection', function (newValue, oldValue) {
更多细节请参阅此link
上的观看示例答案 1 :(得分:0)
通过修改注入方法(如
)来解决问题inject(function (_$controller_, $rootScope) {
$scope = $rootScope.$new();
controller: _$controller_("WatchController", {
$scope: $scope
});