baa*_*der 9 javascript mocha.js requirejs
我在Mocha.js中包含了一个基于Require.js的网站的优秀使用垫片.
在使用Require.js时,如何访问Mocha声明的define()和it()BDD函数?
这是一个基本的代码示例:
test.js:
var mocha = require('use!mocha')
, testFile = require('testFile.js')
mocha.setup('bdd');
mocha.run();
Run Code Online (Sandbox Code Playgroud)
testFile.js:
define(function(require) {
// describe() and it() are not available
describe('Book', function() {
it('should have pages', function() {
});
});
});
Run Code Online (Sandbox Code Playgroud)
我Uncaught ReferenceError: describe is not defined在浏览器中运行时遇到错误.
我尝试过window.describe并尝试将require('testFile.js')移到mocha.setup('bdd')之后.我知道我错过了什么.可能会以某种方式将上下文传递给mocha.
Shu*_*awa 13
问题是全局功能如describe和it设置mocha.setup().您可以在导出mocha之前使用shim config的init属性进行调用mocha.setup().
requirejs.config({
shim: {
'mocha': {
init: function () {
this.mocha.setup('bdd');
return this.mocha;
}
}
}
});
require(['mocha', 'test/some_test'], function (mocha) {
mocha.run();
});
Run Code Online (Sandbox Code Playgroud)
测试文件需要mocha.
define(['mocha'], function (mocha) {
describe('Something', function () {
// ...
});
});
Run Code Online (Sandbox Code Playgroud)
Shim config的init属性是在RequireJS 2.1中引入的.你也许可以使用exports,而不是财产init与RequireJS 2.0.
我在geddski的amd-testing示例项目中找到了解决方案.
而不是将测试文件与mocha一起包含在顶部,如下所示:
define(['use!mocha', 'testFile'],
function(Mocha, TestFile) {
mocha.setup('bdd');
mocha.run();
});
Run Code Online (Sandbox Code Playgroud)
测试文件应作为另一个需求调用包含在内,并且回调中嵌入了mocha.run():
define(['use!mocha'],
function(Mocha) {
mocha.setup('bdd');
// Include the test files here and call mocha.run() after.
require(['testFile'],
function(TestFile) {
mocha.run();
});
});
Run Code Online (Sandbox Code Playgroud)