我正在尝试将控制器测试为vm,但得到错误
主要模块:
(function() {
'use strict';
angular.module('ds', [
'ionic',
'ui.router',
'ds.controllers',
'ds.services',
'ds.filters',
'underscore',
'ionicLazyLoad',
'ngCordova',
'ngIOS9UIWebViewPatch'
])
})();
控制器代码如下:
(function() {
'use strict';
angular
.module('ds')
.controller('LoginCtrl', LoginCtrl);
LoginCtrl.$inject = ["$scope", "$rootScope"];
function LoginCtrl($scope, $rootScope) {
var vm = this;
vm.model = { name: "controllerAs vm test" };
}
})();
我的茉莉花测试:
'use strict';
describe('LoginCtrl', function() {
var LoginCtrl;
beforeEach(module('ds'));
beforeEach(function() {
inject(function($injector) {
LoginCtrl = $injector.get('$controller')('LoginCtrl', {});
});
});
it('LoginCtrl should be defined and LoginCtrl.name is equal to controllerAs vm test', function() {
expect(LoginCtrl).toBeDefined();
expect(LoginCtrl.name).toEqual("controllerAs vm test");
});
});
并收到此错误:
15 11 2016 14:40:33.608:INFO [watcher]: Changed file "/Users/roman.ishchiv/Documents/dogshows/www/modules/login/login.controller.js".
PhantomJS 2.1.1 (Mac OS X 0.0.0) LoginCtrl LoginCtrl should be defined and LoginCtrl.name is equal to controllerAs vm test FAILED
/Users/roman.ishchiv/Documents/dogshows/www/lib/ionic/js/ionic.bundle.js:13218:53
forEach@/Users/roman.ishchiv/Documents/dogshows/www/lib/ionic/js/ionic.bundle.js:9168:24
loadModules@/Users/roman.ishchiv/Documents/dogshows/www/lib/ionic/js/ionic.bundle.js:13178:12
createInjector@/Users/roman.ishchiv/Documents/dogshows/www/lib/ionic/js/ionic.bundle.js:13104:22
workFn@/Users/roman.ishchiv/Documents/dogshows/www/lib/angular-mocks/angular-mocks.js:3074:60
inject@/Users/roman.ishchiv/Documents/dogshows/www/lib/angular-mocks/angular-mocks.js:3054:46
unit-tests/login.controller.test.js:8:15
loaded@http://localhost:9876/context.js:151:17
Expected undefined to be defined.
unit-tests/login.controller.test.js:14:38
loaded@http://localhost:9876/context.js:151:17
TypeError: undefined is not an object (evaluating 'LoginCtrl.name') in unit-tests/login.controller.test.js (line 15)
unit-tests/login.controller.test.js:15:25
loaded@http://localhost:9876/context.js:151:17
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.001 secs / 0.017 secs)
这部分我的业力配置文件:
files: [
'../lib/ionic/js/ionic.bundle.js',
'../lib/angular-mocks/angular-mocks.js',
'../lib/jquery/dist/jquery.js',
'../lib/angular-ui-router/release/angular-ui-router.js',
'../js/*.js',
'../js/**/*.js',
'../modules/**/*.js',
'unit-tests/*.js',
],
有人对如何解决这个问题提出任何建议,或者有关于如何使用John Papa角度风格指南和单元测试的指南?
谢谢!
答案 0 :(得分:1)
我们使用这种构造进行测试(虽然我们使用ES6与ES5):
let vm;
inject((_$controller_, _$rootScope_) => {
vm = _$controller_(SomeControllerImport,
{ $scope: _$rootscope.$new() });
});
然后在您的测试中,您可以像在普通控制器代码中一样直接引用vm:
expect(vm.foo).toHaveBeenCalled();
等等。