javascript Mocha + RequireJS = AMD 测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20473614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:34:46  来源:igfitidea点击:

Mocha + RequireJS = AMD testing

javascriptnode.jsrequirejsmochajs-amd

提问by Oskar Szura

I have a hard time connecting Mocha to RequireJS based application, may be You'll be able to come up with something :). After many hours when I've been trying to load AMD modules and simply console.log some 'fired' info that the module has been loaded... nothing happend had happened - the program just ended and printed out some mocha info.

我很难将 Mocha 连接到基于 RequireJS 的应用程序,也许你会想出一些东西:)。几个小时后,当我一直在尝试加载 AMD 模块并简单地在 console.log 中记录一些模块已加载的“触发”信息......没有发生任何事情 - 程序刚刚结束并打印出一些 mocha 信息。

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

and than I've come up with the idea to fire just this to test callbacks:

然后我想出了这个想法来测试回调:

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

also didn't work. So finally I've run both with

也没有用。所以最后我都跑了

$ node test.js 

and finally it worked. So question is than: How to run Mocha test with callbacks handling, as those are essential for AMD testing?

最后它奏效了。所以问题不是:如何使用回调处理运行 Mocha 测试,因为这些对于 AMD 测试至关重要?

回答by Louis

The way you are doing it, mocha is not going to do anything with your file because it does not see a test suitein it. RequireJS is scheduled to call the callback but mocha exits before this has a chance to happen. Same with your timeout example.

您这样做的方式,mocha 不会对您的文件做任何事情,因为它没有在其中看到测试套件。RequireJS 计划调用回调,但 mocha 在这有机会发生之前退出。与您的超时示例相同。

The following gives you an example.

下面给大家举个例子。

File test.js:

文件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!");
    });
  });
});

File foo.js:

文件foo.js

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

When you run:

当你运行时:

mocha -u tdd test.js

You'll see that the callback is fired and the test passes.

您将看到回调被触发并且测试通过。

For the benefit of people reading this question and confused by the use of suite, suiteSetup, test... Mocha supports multiple interfaces. The code here is using the TDD interface (the OP invokes Mocha with -u tdd), which exports suite, suiteSetup, test, etc. In the default BDD interface, the equivalents are describe, beforeand it, respectively.

对于读书人这个问题,并通过使用混淆了效益suitesuiteSetuptest...摩卡支持多种接口。这里的代码是使用TDD界面(OP所调用摩卡用-u tdd),其出口suitesuiteSetuptest等。在默认的BDD接口,所述等同物describebeforeit分别。

回答by x'ES

I have configured related boilerplate for using mocha in environment of RequireJS. It may be not exact what you want, but it may be helpful. https://github.com/x2es/boilerplate-karma-mocha-chai-requirejs

我已经为在 RequireJS 的环境中使用 mocha 配置了相关的样板。它可能不是您想要的确切内容,但可能会有所帮助。 https://github.com/x2es/boilerplate-karma-mocha-chai-requirejs

One more note - assuming that your script placed in "/public" it makes sense to test it in browser environment instead nodejs. For this purposes you should to look at some test-runner like JsTestDriver (https://code.google.com/p/js-test-driver/) or karma-runner (http://karma-runner.github.io/). Or another...

还有一点要注意 - 假设您的脚本放置在“/public”中,那么在浏览器环境而不是 nodejs 中测试它是有意义的。为此,您应该查看一些测试运行程序,如 JsTestDriver ( https://code.google.com/p/js-test-driver/) 或 karma-runner ( http://karma-runner.github.io /)。或其他...

In snipped provided in karma documentation (http://karma-runner.github.io/0.8/plus/RequireJS.html)

在 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
});

introduced way when we force requirejs to preload all necessary spec-files using

当我们强制 requirejs 使用预加载所有必要的规范文件时引入的方式

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

In this environment each spec-file should be a regular RequireJS module.

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

Example of test spec for such environment:

此类环境的测试规范示例:

define(['chai'], function(chai) {
  var expect = chai.expect;

  describe('bootstrap', function() {
    it('should...', function() {
      expect('a').to.equal('a');
    });
  });
});