我已经设置了Angularjs应用程序,以便与Karma和Jasmin进行单元测试。但是当我尝试使用karma start
运行测试用例时,出现了错误,名为Myctrl
的控制器未注册。
我的应用程序结构如下
project-folder
- app
- components
- controllers
- account
- signInController.js
- SignUpController.js
- app.modules.js
- app.routes.js
- test
这是我的app.modules.js
let app = angular.module( 'app', [
'app.config', 'templates', 'ngAnimate', 'ngAria', 'ngCookies', 'ngMessages', 'ngResource', 'ngSanitize',
'ngTouch', 'ui.router', 'ui.bootstrap', 'ui.utils', 'ui.load', 'ui.jq', 'oc.lazyLoad','angular-cache',
'ngToast', 'ngFileUpload', 'ngFileSaver', 'angularMoment', 'angulartics', 'angulartics.google.analytics',
'ngMessages', 'ng.httpLoader'
]);
还有karma.config.js文件
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'browserify'],
// list of files / patterns to load in the browser
files: [
'dist/libs/jquery/jquery.js',
'dist/libs/angular/angular.js',
'dist/libs/angular-ui-router/angular-ui-router.js',
'dist/libs/angular-sanitize/angular-sanitize.js',
'dist/libs/angular-mocks/angular-mocks.js',
'dist/libs/angular-bootstrap/ui-bootstrap-tpls.js',
'app/app.modules.js',
'app/app.routes.js',
'app/config.lazyload.js',
'app/components/controllers/account/*.js',
'test/**/*spec.js',
],
.
.
describe('Myctrl Test', function() {
describe('Myctrl', function() {
var vm;
beforeEach(inject(function( ) {
angular.module('app')
}));
beforeEach(inject(function(_$rootScope_, $controller) {
var scope = _$rootScope_.$new();
vm = $controller('Myctrl', {$scope: scope});
}));
it('test controller', function() {
expect(vm.title).toBe(null);
});
});
});
app.controller( 'Myctrl', ['$scope', '$state', 'backendApi', 'ngToast', 'access_token', 'FileUploader', 'keys',
function( $scope, $state, backendApi, ngToast, access_token, FileUploader, keys ) {
$scope.title = "Hello";
}])
答案 0 :(得分:0)
在每次测试之前,您必须注册一个模块。
问题是您尝试使用本机AngularJS angular.module('app')
,而必须使用module('app')
,它是angular.mock.module的别名
此功能注册模块配置代码。它收集 进样器处于运行状态时将使用的配置信息 通过注入创建。
将代码更改为
beforeEach(function( ) {
module('app')
});
并确保Myctrl
属于app
模块。
请考虑以下article Testing a Controller
部分。
FYI:angular.module('app')
仅是在angular应用程序中引用模块所必需的,但此功能实际上并不包括模块。