我正在开发一个用 CommonJS 语法编写的 Angular 应用程序,并使用带有 grunt-contrib-requirejs 任务的 grunt 任务将源文件转换为 AMD 格式并将其编译成一个输出文件。我的目标是让 Karma 与 RequireJS 一起工作,并将我的源文件和规范文件保留在 CommonJS 语法中。
我已经能够通过以下文件结构以 AMD 格式通过简单的测试:
-- karma-test
|-- spec
| `-- exampleSpec.js
|-- src
| `-- example.js
|-- karma.conf.js
`-- test-main.js
和以下文件:
业力.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;
例子.js
define('example', function() {
var message = "Hello!";
return {
message: message
};
});
示例规范.js
define(['example'], function(example) {
describe("Example", function() {
it("should have a message equal to 'Hello!'", function() {
expect(example.message).toBe('Hello!');
});
});
});
测试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 语法编写源文件和规范文件,结果相同,如下所示:
例子.js
var message = "Hello!";
module.exports = {
message: message
};
示例规范.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并且有一些评论可能有助于解决这个问题,但我没有任何运气到目前为止。