karma无法加载requirejs注入的文件



我在运行一个简单的因果报应测试时遇到了问题。我有以下代码结构:

js/
  |-- tests.js
  |-- karma.config.js
  |-- app/
         |-- controllers.js
  |-- tests/
         |-- unit/
                 |-- loginSpec.js
  |-- vendor/
         |-- jquery.js

我正在关注文档http://karma-runner.github.io/0.8/plus/RequireJS.html并将我的配置设置如下(减去不重要的部分):

// base path, that will be used to resolve files and exclude
basePath = '';
// list of files / patterns to load in the browser
files = [
    JASMINE,
    JASMINE_ADAPTER,
    REQUIRE,
    REQUIRE_ADAPTER,
    'tests.js',
    {pattern: 'tests/unit/*.js', included: false}
];

在我的controllers.js中,我定义了一个名为LoginCtrl的函数,我想在loginSpec.js 中测试这个函数

define(['controllers'],function(controllers) {
    describe('Login controllers', function() {
        describe('LoginCtrl', function(){
            it('should return 1', function() {
                var scope = {},
                ctrl = new LoginCtrl(scope);
                expect(1).toBe(1);
            });
        });
    });
});

问题是我的浏览器无法加载controllers.js文件,尽管我已经将主测试文件的requirejs配置(tests.js)设置如下:

var tests = Object.keys(window.__karma__.files).filter(function (file) {
      return /Spec.js$/.test(file);
});
requirejs.config({
    baseUrl: '/base/app',
    paths: {
        jquery: 'vendor/jquery',
    },
    deps: tests,
    callback: window.__karma__.start
});

浏览器确实在http://localhost:9876/base/app/controllers.js中查找文件。这不是正确的道路吗?

路径不好,我认为应该是jquery: '../vendor/jquery',因为requirejs的基点指向app目录。但这不是唯一的问题。。。

因果报应,你应该把每个文件都添加到你想要使用的模式中。带有标志include: true的文件将由karma运行,其他文件可用于测试。如果两个模式覆盖一个文件名,那么第一个模式将覆盖第二个模式(所以这与我们通常的顺序相反)。在您的情况下,您应该使用类似的karma.conf.js:

module.exports = function (config) {
    config.set({
        basePath: './',
        frameworks: ['jasmine', 'requirejs'],
        files: [
            {pattern: 'tests.js', included: true},
            {pattern: 'test/**/*.js', included: false},
            {pattern: 'app/**/*.js', included: false},
            {pattern: 'vendor/**/*.js', included: false}
        ],
        exclude: [
        ],
        reporters: ['progress'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['Firefox'],
        captureTimeout: 6000,
        singleRun: false
    });
};

我也遇到过类似的问题,但我没有找到好的解决方案。我不得不通过在我的规范文件中添加.js扩展名来应用"破解",在您的情况下,尝试在您的loginSpec.js 中将"controllers"更改为"controllers.js"

最新更新