首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用CommonJS语法的文件使用Karma和RequireJS进行测试

使用CommonJS语法的文件使用Karma和RequireJS进行测试
EN

Stack Overflow用户
提问于 2013-06-25 01:15:45
回答 2查看 14.7K关注 0票数 16

我正在开发一个使用AMD语法编写的angular应用程序,它使用grunt任务和CommonJS任务将源文件转换为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 repo:https://github.com/karma-runner/karma/issues/552上发现了这个问题,有一些评论可能会对这个问题有所帮助,但到目前为止我还没有任何运气。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-07-02 06:38:10

我最终找到的解决方案涉及到使用grunt和编写一些自定义的任务。过程是这样的:

通过使用文件模式查找所有规范,循环遍历它们并构建传统的AMD风格的require块,然后使用如下代码创建一个临时文件,创建一个grunt任务来构建一个引导程序所需的by文件:

require(['spec/example1_spec.js'
,'spec/example2_spec.js',
,'spec/example3_spec.js'
],function(a1,a2){
// this space intentionally left blank
}, "", true);

创建一个RequireJS grunt任务,该任务编译上述引导程序文件并输出一个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任务配置中看到这一点。

票数 12
EN

Stack Overflow用户

发布于 2013-06-27 03:33:14

有几件事。首先:我可能遗漏了你的问题中的一些细节(因为它是超级大的)-非常抱歉。

简而言之,您可能想检查一下主干样板wip分支测试组织:https://github.com/backbone-boilerplate/backbone-boilerplate/tree/wip

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

Second:Karma requirejs插件运行得并不是很好--而且在某种程度上直接使用requireJS很容易。在BBB上,我们就是这么做的:https://github.com/backbone-boilerplate/backbone-boilerplate/blob/wip/test/jasmine/test-runner.js#L16-L36

希望这能有所帮助!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17281211

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档