javascript 与 Karma 一起运行的 Mocha 单元测试 - done() 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22495028/
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 23:16:24  来源:igfitidea点击:

Mocha unit tests running with Karma - done() is not defined

javascriptunit-testingmochakarma-runnerkarma-mocha

提问by Jason Boyd

I'm trying to get tests written with Mocha to work running Karma, and they sort of work, but I cannot use the done() method to implement async tests, which essentially makes the tools useless to me. What am I missing?

我正在尝试使用 Mocha 编写测试来运行 Karma,并且它们可以正常工作,但是我无法使用 done() 方法来实现异步测试,这基本上使这些工具对我毫无用处。我错过了什么?

karma.conf.js

业力配置文件

module.exports = function(config) {
  config.set({
    basePath: '../..',
    frameworks: ['mocha', 'requirejs', 'qunit'],
    client: {
        mocha: {
            ui: 'bdd'
        }
    },
    files: [
      {pattern: 'libs/**/*.js', included: false},
      {pattern: 'src/**/*.js', included: false},
      {pattern: 'tests/mocha/mocha.js', included: false},
      {pattern: 'tests/should/should.js', included: false},
      {pattern: 'tests/**/*Spec.js', included: false},
      'tests/karma/test-main.js'
    ],
    exclude: [
      'src/main.js'
    ],
    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress', 'dots'],
    port: 9876,
    colors: true,
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_WARN,
    autoWatch: true,
    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera (has to be installed with `npm install karma-opera-launcher`)
    // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
    // - PhantomJS
    // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
    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
  });
};

test-main.js (configuring RequireJS)

test-main.js(配置RequireJS)

var allTestFiles = [];
var pathToModule = function(path) {
  return path.replace(/^\/base\//, '../').replace(/\.js$/, '');
};

Object.keys(window.__karma__.files).forEach(function(file) {
  if (/Spec\.js$/.test(file)) {
    // Normalize paths to RequireJS module names.
    allTestFiles.push(pathToModule(file));
  }
});

require.config({
  // Karma serves files under /base, which is the basePath from your config file
  baseUrl: '/base/src',
  paths: {
    'should': '../tests/should/should',
    'mocha': '../tests/mocha/mocha',
    'pubsub': '../libs/pubsub/pubsub',
    'jquery': '../libs/jquery/jquery-1.10.2',
    'jquery-mobile': '//code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min'
  },
  // dynamically load all test files
  deps: allTestFiles, 
  // we have to kickoff jasmine, as it is asynchronous
  callback: window.__karma__.start
});

tests/fooSpec.js

测试/fooSpec.js

define(['music/note'], function(Note) {

describe('nothing', function(done) {
    it('a silly test', function() {
        var note = new Note;
        note.should.not.eql(32);
    });
    done();
});
...

Though this is a contrived example, it succeeds if I remove the done() call. As it is, I get:

虽然这是一个人为的例子,但如果我删除 done() 调用,它就会成功。照原样,我得到:

Uncaught TypeError: undefined is not a function
at /Library/WebServer/Documents/vg/tests/mocha/fooSpec.js:8

This is the done() line. How/why is this not defined? I'm not understanding where else to configure Mocha (or with what options). Is there some sort of global namespace or meta-programming magic causing RequireJS to interfere with Mocha?

这是 done() 行。如何/为什么这没有定义?我不明白还有什么地方可以配置 Mocha(或使用什么选项)。是否有某种全局命名空间或元编程魔法导致 RequireJS 干扰 Mocha?

I'm running the tests in Chrome 33 on OS X 10.9.2, in case that is at all relevant. I've killed a ton of time on this and am ready to give up on automated testing :( -- had similar brick walls with QUnit/Karma/RequireJS and have not been able to find any alternative to successfully automate tests. I feel like an idiot.

我正在 OS X 10.9.2 上的 Chrome 33 中运行测试,以防万一。我已经为此花费了大量时间,并准备放弃自动化测试 :( -- 与 QUnit/Karma/RequireJS 有类似的砖墙,并且无法找到成功自动化测试的任何替代方法。我觉得一个白痴。

回答by Louis

In Mocha, the donecallback is for it, before, after, beforeEach, afterEach. So:

在 Mocha 中,done回调用于it, before, after, beforeEach, afterEach。所以:

describe('nothing', function() {
    it('a silly test', function(done) {
        var note = new Note;
        note.should.not.eql(32);
        done();
    });
});

Here's the doc.

这是文档

回答by Jason Boyd

Holy %$#@!

神圣的%$#@!

I would never in a million years have thought this would barf:

一百万年后,我永远不会想到这会让人呕吐:

describe('nothing', function(done) {
    it('umm...', function() {
        var note = new Note;
        note.should.not.eql(32);
    });
    done(); // throws error that undefined is not a function
});

But this works just fine:

但这工作得很好:

describe('nothing', function(done) {
    it('umm...', function() {
        var note = new Note;
        note.should.not.eql(32);
    });
    setTimeout(function() {
        done();  // MAGIC == EVIL.
    }, 1000);
});

回答by startswithaj

The test you are running in that example doesn't require the done() callback. It is not asynchronous. An example of when the done callback is need....

您在该示例中运行的测试不需要 done() 回调。它不是异步的。何时需要完成回调的示例....

describe('Note', function() {
    it('can be retrieved from database', function(done) {
        var note = new Note();
        cb = function(){
           note.contents.should.eql("stuff retrieved from database");
           done()
        }
        //cb is passed into the async function to be called when it's finished
        note.retrieveFromDatabaseAsync(cb)
    });
});

Your test should not have a done callback

你的测试不应该有一个完成的回调

describe('nothing', function() {
    it('umm...', function() {
        var note = new Note;
        note.should.not.eql(32);
    });

});

Only the 'it' function provides a done callback. describe does not. Your problem does not rest with karma. Your mocha tests are not defined correctly.

只有“it”函数提供完成回调。描述没有。你的问题不在于业力。您的 mocha 测试定义不正确。