问题描述
我可以在浏览器中异步加载mocha模块吗?我可以肯定地用柴做。是否有任何解决方法使mocha以类似amd的方式工作?
Can I load mocha module asynchronously in browser? I can do it for sure with chai. Is there any workaround to make mocha work in amd-like style ?
require.config({
baseUrl: "/scripts",
paths: {
"mocha": "framework/mocha",
"chai": "framework/chai",
"first": "custom/first"
}
});
require(['first', 'mocha', 'chai'], function (first, mocha, chai) {
first.echo();
console.log('something');
console.log('something');
mocha.ui('tdd');
var assert = chai.assert;
suite('"Home" Page Tests', function () {
test('page should contain link to contact page', function () {
assert($('a[href="/contact"]').length);
});
});
mocha.run();
console.log('whatever');
});
首先
和 chai
工作正常,而 mocha
未定义。
in the code sample above first
and chai
work fine, while mocha
is undefined.
推荐答案
Mocha不支持AMD,所以如果你要使用RequireJS加载Mocha,你需要一个 shim
。这是一个 index.html
文件,其中包含一个最小示例:
Mocha is not AMD-aware so if you are going to load Mocha using RequireJS, you need a shim
for it. Here is an index.html
file that contains a minimal example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8"/>
<link href="node_modules/mocha/mocha.css" type="text/css" media="screen" rel="stylesheet" />
<script type="text/javascript" src="node_modules/requirejs/require.js"></script>
</head>
<body>
<div id="mocha"></div>
<script>
require.config({
paths: {
mocha: 'node_modules/mocha/mocha',
},
shim: {
mocha: {
exports: "mocha",
}
},
});
require(["mocha"], function (mocha) {
mocha.setup("bdd");
it("foo", function () {});
mocha.run();
});
</script>
</body>
</html>
你需要运行 npm install requirejs mocha
在 index.html
所在的同一目录中。
You need to have run npm install requirejs mocha
in the same directory where index.html
is located.
如果我想能够使用 Mocha
构造函数我使用此 shim
代替:
In cases where I want to be able to use the Mocha
constructor I use this shim
instead:
shim: {
mocha: {
exports: "mocha",
init: function () { return {mocha: mocha, Mocha: Mocha }; }
}
},
这篇关于异步运行mochajs(类似AMD)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!