我现在正在使用mocha进行javascript单元测试。
我有几个测试文件,每个文件都有一个before和beforeEach,但它们完全相同。
如何提供一个全球性的before,并beforeEach为所有的人(或其中的一些)?
Answers:
在单独的文件中声明一个before或beforeEach(我使用spec_helper.coffee)并要求它。
spec_helper.coffee
afterEach (done) ->
  async.parallel [
    (cb) -> Listing.remove {}, cb
    (cb) -> Server.remove {}, cb
  ], ->
    done()
test_something.coffee
require './spec_helper'
    在test文件夹的根目录中,创建一个全局测试助手test/helper.js,其中包含您的before和beforeEach
// globals
global.assert = require('assert');
// setup
before();
beforeEach();
// teardown
after();
afterEach();
    从摩卡文档中...
根目录挂钩
您也可以选择任何文件并添加“根”级挂钩。例如,在所有describe()块之外添加beforeEach()。这将使对beforeEach()的回调在任何测试用例之前运行,无论其位于哪个文件中(这是因为Mocha具有隐式describe()块,称为“根套件”
describe()首先收集所有常规套件,然后运行,这可以确保首先调用它。
'use strict'
let run = false
beforeEach(function() {
    if ( run === true ) return
    console.log('GLOBAL ############################')
    run = true
});
如果希望每次运行之前都看到它运行,请删除运行标志。
我命名了这个文件test/_beforeAll.test.js。它不需要在任何地方导入/请求,但是文件名中的.test.(resp。.spec.)很重要,因此您的测试运行人员可以将其选中...
mocha.opts\ o /如果有东西,您真的只想在运行测试之前设置一次(无论哪个...),这mocha.opts是一个令人惊讶的优雅选择!–只需require在文件中添加一个(是的,即使它对Mocha的贡献很小,但对您的测试设置也没有影响)。它将可靠地运行一次:
(在此示例中,我检测到是否要运行单个测试或多个测试。在前一种情况下,我输出every log.info(),而在完整运行时,我将冗长程度降低为error + warn ...)
更新:
如果有人知道一种方法,可以访问即将在中运行的Mocha套件的一些基本属性once.js,我很想知道并在此处添加。(即,我的suiteMode检测很糟糕,如果还有另一种检测方法,则要运行多少个测试…)
当我需要“模拟”依赖项之一使用的全局变量时,我遇到了类似的问题。
我之所以使用.mocharc.js,是因为在设置“ mocha”环境时,该JS文件中的代码会执行一次。
示例.mocharc.js:
global.usedVariable = "someDefinedValue";
/** other code to be executed when mocha env setup **/
module.exports = {};
这对我有用,但是这样做看起来很“肮脏”。请发表评论,如果您知道该代码的更好位置:)
使用模块可以使测试套件的全局设置/拆卸更加容易。这是使用RequireJS(AMD模块)的示例:
首先,让我们通过全局设置/拆卸定义测试环境:
// test-env.js
define('test-env', [], function() {
  // One can store globals, which will be available within the
  // whole test suite.
  var my_global = true;
  before(function() {
    // global setup
  });
  return after(function() {
    // global teardown
  });
});
在我们的JS运行程序(包含在mocha的HTML运行程序中,以及其他的库和测试文件,以及<script type="text/javascript">…</script>作为外部JS文件(或更好的形式))中:
require([
          // this is the important thing: require the test-env dependency first
          'test-env',
          // then, require the specs
          'some-test-file'
        ], function() {
  mocha.run();
});
some-test-file.js 可以这样实现:
// some-test-file.js
define(['unit-under-test'], function(UnitUnderTest) {
  return describe('Some unit under test', function() {
    before(function() {
      // locally "global" setup
    });
    beforeEach(function() {
    });
    afterEach(function() {
    });
    after(function() {
      // locally "global" teardown
    });
    it('exists', function() {
      // let's specify the unit under test
    });
  });
});