摩卡+ RequireJS = AMDtesting

我有一个很难将摩卡连接到基于RequireJS的应用程序,可能你会想出一些东西:)。 几个小时后,我一直试图加载AMD模块,只是console.log一些'已解除'的信息,该模块已被加载…没有发生事情发生了 – 程序刚刚结束,打印出一些摩卡信息。

var facade = requirejs(['../../public/js/scripts/widgets/widgets/article/main.js'], function(mod) { console.log('fired') }); // run with: $ mocha -u tdd test.js --reporter spec 

而且我想出了这个想法来testingcallback:

 setTimeout((function() { console.log('fired'); }), 5000); // run with: $ mocha -u tdd test.js --reporter spec 

也没有工作。 所以最后我已经跑了

 $ node test.js 

最后它的工作。 所以问题是: 如何使用callback处理来运行Mochatesting,因为这些对于AMDtesting是必不可less的。

摩卡是这样做的,不会对你的文件做任何事情,因为它没有看到它的testing套件 。 RequireJS计划调用callback函数,但在有机会发生之前,摩卡会退出。 与您的超时示例相同。

以下给出一个例子。

文件test.js

 'use strict'; var requirejs = require("requirejs"); requirejs.config({ baseUrl: '.', nodeRequire: require }); suite('Something', function(){ var foo; suiteSetup(function (done){ // This saves the module foo for use in tests. You have to use // the done callback because this is asynchronous. requirejs(['foo'], function(mod) { console.log("fired!"); foo = mod; done(); }); }); suite('blah', function(){ test('blah', function(){ if (foo.test !== "test") throw new Error("failed!"); }); }); }); 

档案foo.js

 define(function () { return {test: "test"}; }); 

当你运行:

 mocha -u tdd test.js 

你会看到callback被触发,testing通过。

为了阅读这个问题的人们的利益,并使用suitesuiteSetuptest …混淆摩卡支持多接口。 这里的代码使用TDD接口(OP调用Mocha和-u tdd ),它导出suitesuiteSetuptest等等。在默认的BDD接口中,等价物分别beforeit describe

我在RequireJS的环境中configuration了使用摩卡的相关样板。 这可能不是你想要的,但可能有帮助。 https://github.com/x2es/boilerplate-karma-mocha-chai-requirejs

还有一点需要注意的是,假设你的脚本放置在“/ public”中,在浏览器环境中而不是nodejs中testing它是有意义的。 为此,你应该看看像JsTestDriver( https://code.google.com/p/js-test-driver/ )或karma-runner( http://karma-runner.github.io / )。 或其他…

在karma文档中提供的剪切( http://karma-runner.github.io/0.8/plus/RequireJS.html

 var tests = []; for (var file in window.__karma__.files) { if (window.__karma__.files.hasOwnProperty(file)) { if (/Spec\.js$/.test(file)) { tests.push(file); } } } requirejs.config({ // Karma serves files from '/base' baseUrl: '/base/src', paths: { 'jquery': '../lib/jquery', 'underscore': '../lib/underscore', }, shim: { 'underscore': { exports: '_' } }, // ask Require.js to load these files (all our tests) deps: tests, // start test run, once Require.js is done callback: window.__karma__.start }); 

当我们强迫requirejs使用所有必要的spec文件时,引入了这种方式

 require.config({ deps: ['array', 'of', 'our', 'spec', 'files'] }) 

在这种环境下,每个spec文件应该是一个常规的RequireJS模块。

此类环境的testing规范示例:

 define(['chai'], function(chai) { var expect = chai.expect; describe('bootstrap', function() { it('should...', function() { expect('a').to.equal('a'); }); }); });