我有一个像下面的控制器
(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)
最佳答案
将监视行代码更新为:
$scope.$watch('options.rowSelection', function (newValue, oldValue) {
更详细的内容请参见此link上的观看示例
关于javascript - 在 Controller 中放置 watch 时出现 Angular UT问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37202519/