我无法使用 require 和 karma 为我的 AngularJS 应用程序编写测试。从 karma 加载主源文件时,我随机收到“未定义模块”错误,我不确定为什么。
我的项目结构如下:
main
-webapp
-components
-{all my external libs}
-js
-{my js files}
test
-lib
angular-mocks.js
underscore.js
-webapp
karma.conf.js
server.js
test-main.js -> require js config
-unit
myTest.js
我的 test-main.js 定义如下 -
var tests = [];
for (var file in window.__karma__.files) {
if (/Test\.js$/.test(file)) {
tests.push(file);
console.log(file);
}
}
requirejs.config({
baseUrl:'base/',
paths:{
'angular':'main/webapp/components/angular-1.0.7',
'jquery':'main/webapp/components/jquery',
'jquery-ui':'main/webapp/components/jquery-ui',
'lodash':'main/webapp/components/lodash',
'underscore':'test/webapp/lib/underscore',
'angular-mocks':'test/webapp/lib/angular-mocks',
'requireLibChecker':'test/webapp/checker/requireLibChecker',
'bootstrap':'main/webapp/components/bootstrap/js/bootstrap',
'bootstrap-datepicker':'main/webapp/components/bootstrap/js/bootstrap-datepicker',
'app':'main/webapp/js/mcc',
'helper':'main/webapp/js/helper',
'js':'main/webapp/js'
},
shim:{
'angular':{
exports:'angular'
},
'angular-mocks':{
exports:'angular-mocks'
},
'underscore':{
exports:'_'
},
'jquery-ui':{
deps:['jquery'],
exports:'jquery-ui'
},
'bootstrap-datepicker':{
deps:['jquery', 'bootstrap'],
exports:'datepicker'
}
},
priority:[
"angular"
],
// ask Require.js to load these files (all our tests)
deps:tests,
priority:['angular'],
// start test run, once Require.js is done
callback:window.__karma__.start
});
我的主要第一个源文件(mcc.js)在通过 karma 加载时导致错误,定义如下:
define("app", [
'angular',
'js/controllers/overviewctrl',
'js/controllers/topicactivityctrl',
'js/services/transportmodel',
'js/services/subjectmodel',
'js/directives/controlsdirective',
'bootstrap-datepicker',
'jquery-ui'
], function(angular) {
var app = angular.module('mcc', []).config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/overview', {
templateUrl:'partials/system-overview.html',
controller: 'OverviewController'
}).
when('/overview/:systemId', {
templateUrl:'partials/system-overview.html',
controller: 'OverviewController'
}).
otherwise({redirectTo:'/overview'});
}]);
app.controller("AppController", ['$rootScope', 'transportModel', function($rootScope, transportModel) {
$rootScope.$on("$routeChangeError", function(event, current, previous, rejection) {
alert("Route Change Error: " + rejection);
});
if ($rootScope.mcc_region === undefined)
$rootScope.mcc_region = "New York";
transportModel.then(function(tm) {
$rootScope.mcc_regions = tm.regions;
});
}]);
return app;
});
require(['angular', 'helper'], function(angular, helper) {
angular.element(document).ready(function() {
/* MANUALLY LOAD TO WAIT FOR APP */
angular.bootstrap(document, ['mcc']); --> This line causes the error
/* NAVIGATE TO TOP OF PAGE FOR MOBILE DEVICES */
window.scrollTo(0, 1);
});
});
我正在尝试调试确切的原因 -
angular.bootstrap(document, ['mcc']); 随机导致错误——也就是说,有时浏览器(chrome、phantomJS)会找到模块,有时在通过业力运行时找不到。如果我将它作为常规网络应用程序运行,它第一次总是可以正常工作。