全球`before`和`beforeEach`的摩卡?(Global `before` and `b

2019-07-29 09:01发布

我使用的是摩卡JavaScript的单元测试了。

我有几个测试文件,每个文件都有一个beforebeforeEach ,但它们是完全一样的。

如何提供一个全球性的beforebeforeEach为所有这些(或其中的一些)?

Answer 1:

一个声明beforebeforeEach在一个单独的文件(我用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'


Answer 2:

在测试文件夹的根目录,创建一个全球性的试验辅助test/helper.js其中有你之前和beforeEach

// globals
global.assert = require('assert');

// setup
before();
beforeEach();

// teardown
after();
afterEach();


Answer 3:

从摩卡文档 ...

根级别挂钩

您也可以选择任何文件,并添加“根”级挂钩。 例如,添加beforeEach()以外的所有描述()块。 这将导致回调beforeEach()之前的任何测试的情况下,运行无论其居住在该文件的(这是因为摩卡已经隐含说明()块,被称为“根套件

所有正规describe() -suites首先收集, 然后才运行,这还挺保证这之中第一次调用。

'use strict'
let run = false

beforeEach(function() {
    if ( run === true ) return
    console.log('GLOBAL ############################')
    run = true
});

每次测试前取下运行标志,如果你想看到它每次运行。

我命名这个文件test/_beforeAll.test.js 。 它没有必要进口/需要的任何地方,但.test. (相应.spec.在文件名)是很重要的,让你的TestRunner捡起来......


奖金轨道8):使用mocha.opts \ O /

如果有东西,你真的只需要运行测试(无论哪一个?)之前设置一次, mocha.opts是一个令人惊讶的优雅的选择! -只需添加一个require到您的文件(是的,即使它贡献甚微摩卡,而是测试设置)。 它将运行之前可靠一次:

(在这个例子中,我发现,如果单个测试或多次测试即将运行。在前一种情况下我每输出log.info()而在一个完整的运行我减少冗长的错误+警告...)

更新:

如果有人知道的方式,访问摩卡套件即将在将要运行的一些基本属性once.js ,我很想知道,并添加在这里。 (即我suiteMode -检测是糟糕的,如果有另一种方式来检测,有多少测试来运行...)



Answer 4:

使用的模块可以更容易地为您的测试套件在全球安装/拆卸。 下面是使用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亚军(包括在摩卡的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
    });
  });
});


文章来源: Global `before` and `beforeEach` for mocha?