karma.conf.js自动文件排序?

dus*_*ltz 7 jasmine phantomjs angularjs karma-runner karma-jasmine

我有一个按功能排序的大型angularjs项目.我想设置单元测试,但是我无法获得karma.conf.js文件的排序设置.

我尝试指定一个简单的glob模式,如**/*.js,但是我的许多模块都因为在运行时包含在Karma中的顺序而无法加载.据我所知,这是按字母顺序排列的第一场比赛.

我能够通过这样做来手动计算排序来解决这个问题:

// list of files / patterns to load in the browser
files: [
  // External scripts
  'bower_components/angular/angular.js',
  'bower_components/angular-mocks/angular-mocks.js',
  'bower_components/angular-cookies/angular-cookies.js',
  'bower_components/angular-resource/angular-resource.js',
  'bower_components/angular-route/angular-route.js',

  // NOTE: ORDER IS IMPORTANT
  // Modules: load module first, then all controllers, services, etc
  'scripts/module1/module1.js',
  'scripts/module1/**/*.js',
  'scripts/module2/module2.js',
  'scripts/module2/**/*.js',

  // Load overall app module last
  'scripts/app.js',

  // Load mocks and tests
  'test/mock/**/*.js',
  'test/spec/**/*.js'
],
Run Code Online (Sandbox Code Playgroud)

随着时间的推移,随着新模块的添加,这似乎很麻烦.有没有办法自动解决订购?

注意:我想到的一个可能的解决方案是将所有文件连在一起,但我搜索了一下是否其他人正在这样做并且没有找到任何示例.

Mar*_*coL 6

我认为您可以在此处查看不同的解决方案,具体取决于您希望如何管理项目.

解决方案n.1

使用AMD/RequireJS:不要一次性加载模块,而是在需要时只需要它们.有时它可能不适合您的需求,使项目过于复杂,所以请看下面.

注意:这是恕我直言最优雅的解决方案,业力确实支持requireJS.

解决方案n.2

创建一个命名空间,您可以在其中附加所有内容并在DOM准备就绪时启动它们(通常非常快,但这实际上取决于您加载的脚本数量)

// module A
// Something like this should be fine
(function(){
  window.MyNamespace = window.MyNamespace || {};
  // append things to the namespace...
})();

// module B
(function(){
  window.MyNamespace = window.MyNamespace || {};
  // append things to the namespace...
})();

// This is very rough but it should give the idea
window.ondomready = MyNamespace.start;
Run Code Online (Sandbox Code Playgroud)

注意:虽然这可能有效,但您必须在项目中稍微改变结构.

除非你真的讨厌requireJS和所有模块,否则我会选择上面的那个.

解决方案n.3

以编程方式订购您的Karma文件:我在这里回答了这个问题.

注意:这是不太可能的选项.