我有一个示例角度应用程序,如下所示
(function () {
angular.module("WatchApp", [])
.controller("WatchController", function ($scope) {
$scope.message = "hello";
});
}());
我有一个如下所示的测试用例
describe("WatchController", function () {
var $scope;
beforeEach(module("WatchApp"));
beforeEach(
inject(function (_$controller_) {
$scope: {};
controller: _$controller_("WatchController", {
$scope: $scope
});
}));
describe("Initialization", function () {
it("Should be truthy", function () {
expect(true).toBeTruthy();
})
})
});
我知道测试用例不对,只是写了看配置是否正确,但它总是给出如下错误
PhantomJS 2.1.1 (Windows 7 0.0.0) WatchController Initialization Should be truthy FAILED
TypeError: undefined is not an object (evaluating '$scope.message = "hello"') (line 5)
C:/robin/Studies/Angularjs/ut/app/controllers/watchController.js:5:19
[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:9: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:7:15
global code@C:/robin/Studies/Angularjs/ut/test/controllers/watchControllerSpec.js:1:9
请让我知道问题是什么
答案 0 :(得分:0)
试试这个
inject(function (_$controller_, _$scope_) {
$scope: _$scope_;
controller: _$controller_("WatchController", {
'$scope': $scope
});
}));
答案 1 :(得分:0)
确保在测试中正确注入并使用$rootScope
。
describe("WatchController", function () {
var $scope,
$controller;
beforeEach(module("WatchApp"));
beforeEach(
inject(function (_$controller_, _$rootScope_) {
$scope = _$rootScope_.$new();
$controller = _$controller_("WatchController", {
$scope: $scope
});
}));
describe("Initialization", function () {
it("Should be truthy", function () {
expect(true).toBeTruthy();
});
it("should set a message", function () {
expect($scope.message).toBe("hello");
});
});
});
答案 2 :(得分:0)
通过更改
修复了问题inject(function (_$controller_) {
$scope: {};
controller: _$controller_("WatchController", {
$scope: $scope
});
到
inject(function (_$controller_) {
$scope= {};
controller: _$controller_("WatchController", {
$scope: $scope
});