使用Karma和RequireJS进行测试,文件采用CommonJS语法

16

我正在开发一个Angular应用程序,它使用CommonJS语法编写,并且使用grunt任务和grunt-contrib-requirejs任务将源文件转换为AMD格式并编译成一个输出文件。我希望让Karma能够与RequireJS配合使用,并且保持我的源文件和规范文件的CommonJS语法。

我已经成功地使用以下文件结构在AMD格式下通过了一个简单的测试:

-- karma-test
   |-- spec
   |   `-- exampleSpec.js
   |-- src
   |   `-- example.js
   |-- karma.conf.js
   `-- test-main.js

还有以下文件:

karma.conf.js

// 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,
  'test-main.js',
  {pattern: 'src/*.js', included: false},
  {pattern: 'spec/*.js', included: false}
];

// list of files to exclude
exclude = [];

// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress'];

// web server port
port = 9876;

// cli runner port
runnerPort = 9100;

// enable / disable colors in the output (reporters and logs)
colors = true;

// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_DEBUG;

// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;

// Start these browsers, currently available:
browsers = ['Chrome'];

// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;

// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;

example.js

define('example', function() {
    var message = "Hello!";

    return {
        message: message
    };
});

exampleSpec.js

define(['example'], function(example) {
    describe("Example", function() {
        it("should have a message equal to 'Hello!'", function() {
            expect(example.message).toBe('Hello!');
        });
    });
});

test-main.js

var tests = Object.keys(window.__karma__.files).filter(function (file) {
      return /Spec\.js$/.test(file);
});

requirejs.config({
    // Karma serves files from '/base'
    baseUrl: '/base/src',

    // Translate CommonJS to AMD
    cjsTranslate: true,

    // ask Require.js to load these files (all our tests)
    deps: tests,

    // start test run, once Require.js is done
    callback: window.__karma__.start
});

然而,我的目标是用CommonJS语法编写源文件和规范文件,并产生相同的结果,如下所示:

example.js

var message = "Hello!";

module.exports = {
    message: message
};

exampleSpec.js

var example = require('example');

describe("Example", function() {
    it("should have a message equal to 'Hello!'", function() {
        expect(example.message).toBe('Hello!');
    });
});

但是尽管已经将cjsTranslate标志设置为true,我仍然收到这个错误:

Uncaught Error: Module name "example" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
at http://localhost:9876/adapter/lib/require.js?1371450058000:1746

有没有任何想法可以实现这个?


编辑:我在karma-runner仓库中找到了这个问题:https://github.com/karma-runner/karma/issues/552,里面有一些评论可能对解决这个问题有帮助,但我迄今为止还没有成功。


2个回答

12
我最终找到的解决方案涉及使用grunt并编写一些自定义grunt任务。该过程如下:
创建一个grunt任务,通过查找所有使用文件模式的规范,循环遍历它们并构建传统的AMD样式require块,创建一个临时文件,其中包含以下代码:
require(['spec/example1_spec.js'
,'spec/example2_spec.js',
,'spec/example3_spec.js'
],function(a1,a2){
// this space intentionally left blank
}, "", true);

创建一个RequireJS grunt任务,编译上述bootstrap文件,并输出一个单独的js文件,该文件将有效地包含所有源代码、规范和库。
   requirejs: {
        tests: {
            options: {
                baseUrl: './test',
                paths: {}, // paths object for libraries
                shim: {}, // shim object for non-AMD libraries
                // I pulled in almond using npm
                name: '../node_modules/almond/almond.min',
                // This is the file we created above
                include: 'tmp/require-tests',
                // This is the output file that we will serve to karma
                out: 'test/tmp/tests.js',
                optimize: 'none',
                // This translates commonjs syntax to AMD require blocks
                cjsTranslate: true
            }
        }
    }
创建一个grunt任务,手动启动karma服务器并提供单个编译后的js文件进行测试。此外,我能够放弃在karma.conf.js文件中使用REQUIRE_ADAPTER,并且只包含单个编译后的js文件而不是匹配所有源代码和规范的模式,因此现在看起来像这样:
// 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,
  'tmp/tests.js'
];

// list of files to exclude
exclude = [];

// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress'];

// web server port
port = 9876;

// cli runner port
runnerPort = 9100;

// enable / disable colors in the output (reporters and logs)
colors = true;

// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;

// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;

// Start these browsers, currently available:
browsers = ['PhantomJS'];

// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;

// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = true;

在requirejs编译的grunt任务配置中,还需要使用almond来启动测试执行(如果没有它,测试执行会卡住)。您可以在上面的requirejs grunt任务配置中看到它的使用。

1

有几件事情。首先:由于您的问题非常庞大,我可能错过了一些细节 - 对此深表歉意。

简而言之,您可能想要查看Backbone-Boilerplate wip分支测试组织: https://github.com/backbone-boilerplate/backbone-boilerplate/tree/wip

第一点:RequireJS不支持未包装的原始common.js模块。cjsTranslate是R.js(构建工具)选项,在构建过程中将Commonjs转换为AMD兼容。因此,需要CJS原始模块是行不通的。要解决此问题,您可以使用服务器过滤发送的脚本并将其编译为AMD格式。在BBB上,我们通过静态服务传递文件来编译它们:

第二点: Karma requirejs插件的效果并不是很好,而且直接使用requireJS很容易。在BBB上,我们就是这样管理的: https://github.com/backbone-boilerplate/backbone-boilerplate/blob/wip/test/jasmine/test-runner.js#L16-L36

希望这可以帮到你!


BBB链接已经失效,请转至同一文件重命名的提交链接:https://github.com/backbone-boilerplate/backbone-boilerplate/blob/eb172e0ac9accb16d1d46e288052be0bded052bb/test/runner.js - MrYellow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接