Javascript 摩卡的全局“before”和“beforeEach”?

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

Global `before` and `beforeEach` for mocha?

javascriptunit-testingmocha

提问by Freewind

I'm using mocha for javascript unit-testing now.

我现在正在使用 mocha 进行 javascript 单元测试。

I have several test files, each file has a beforeand beforeEach, but they are exactly the same.

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

How do I provide a global beforeand beforeEachfor all of them (or some of them)?

如何提供一个全球性的before,并beforeEach为所有的人(或其中的一些)?

采纳答案by Michelle Tilley

Declare a beforeor beforeEachin a separate file (I use spec_helper.coffee) and require it.

在单独的文件(我使用)中声明 abefore或并需要它。beforeEachspec_helper.coffee

spec_helper.coffee

spec_helper.coffee

afterEach (done) ->
  async.parallel [
    (cb) -> Listing.remove {}, cb
    (cb) -> Server.remove {}, cb
  ], ->
    done()

test_something.coffee

test_something.coffee

require './spec_helper'

回答by AJcodez

In the root of the test folder, create a global test helper test/helper.jswhich has your before and beforeEach

在 test 文件夹的根目录中,创建一个全局测试助手test/helper.js,其中包含您的 before 和 beforeEach

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

// setup
before();
beforeEach();

// teardown
after();
afterEach();

回答by Frank Nocke

from the mocha documentation

来自摩卡文档……

ROOT-LEVEL HOOKS

You may also pick any file and add “root”-level hooks. For example, add beforeEach() outside of all describe() blocks. This will cause the callback to beforeEach() to run before any test case, regardless of the file it lives in (this is because Mocha has an implied describe() block, called the “root suite

根级挂钩

您还可以选择任何文件并添加“根”级挂钩。例如,在所有 describe() 块之外添加 beforeEach()。这将导致对 beforeEach() 的回调在任何测试用例之前运行,无论它位于哪个文件中(这是因为 Mocha 有一个隐含的 describe() 块,称为“根套件”

All regular describe()-suites are first collected and only thenrun, this kinda guarantees this being called first.

describe()首先收集所有常规-suites,然后才运行,这有点保证首先调用它。

'use strict'
let run = false

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

Remove the run-flag, if you want to see it run each time, before every test.

如果您想在每次测试之前每次都看到它运行,请删除运行标志。

I named this file test/_beforeAll.test.js. It has no need to be imported/required anywhere, but the .test.(resp. .spec.) in the filename is important, so that your testrunner picks it up…

我将这个文件命名为test/_beforeAll.test.js. 它不需要在任何地方导入/需要,但文件名中的.test.(resp. .spec.) 很重要,这样你的测试运行器就会把它捡起来……



bonus track 8-): using mocha.opts\o/

奖励曲目 8-):使用mocha.opts\o/

If there's stuff, you truly only want to set up once before running your tests (regardless which ones...), mocha.optsis a surprisingly elegant option! – Just add a requireto your file (yes, even if it contributes little to mocha, but rather to your test setup). It will run reliably once before:

如果有东西,你真的只想在运行你的测试之前设置一次(不管是什么......),这mocha.opts是一个非常优雅的选择!– 只需require在您的文件中添加一个(是的,即使它对 mocha 的贡献很小,但对您的测试设置却有贡献)。它之前会可靠地运行一次:

enter image description here

在此处输入图片说明

( in this example I detect, if a single test or many tests are about to run. In the former case I output every log.info(), while on a full run I reduce verbosity to error+warn... )

(在本例中,我检测是否将要运行单个测试或多个测试。在前一种情况下,我输出每个log.info(),而在完整运行时,我将详细程度减少为错误+警告...)

Update:

更新:

If someone knows a way, to access some basic properties of the mocha suite that is about to be run in once.js, I would love to know and add here. (i.e. my suiteMode-detection is lousy, if there was another way to detect, how many tests are to be run…)

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

回答by Aleksey Moroz

I've had similar issue when I needed to "mock" global variables used by one of dependencies.

当我需要“模拟”依赖项之一使用的全局变量时,我遇到了类似的问题。

I used .mocharc.js for that, since code in that JS file is being executed once when "mocha" environment is being setup.

我为此使用了 .mocharc.js,因为在设置“mocha”环境时,该 JS 文件中的代码将被执行一次。

Example .mocharc.js:

示例 .mocharc.js:

global.usedVariable = "someDefinedValue";

/** other code to be executed when mocha env setup **/

module.exports = {};

This worked for me, nevertheless this looks quite "dirty" way to do that. Please, comment if you know a better place for that code :)

这对我有用,但是这看起来很“肮脏”的方式来做到这一点。如果您知道该代码的更好位置,请发表评论:)

回答by chikamichi

The use of a modules can make it easier to have a global setup/teardown for your test suite. Here is an example using RequireJS (AMD modules):

使用模块可以更轻松地为您的测试套件进行全局设置/拆卸。下面是一个使用 RequireJS(AMD 模块)的例子:

First, let's define a test environment with our global setup/teardown:

首先,让我们使用全局设置/拆卸定义一个测试环境:

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

In our JS runner (included in mocha's HTML runner, along the other libs and test files, as a <script type="text/javascript">…</script>, or better, as an external JS file):

在我们的 JS 运行器中(包含在 mocha 的 HTML 运行器中,以及其他库和测试文件,作为<script type="text/javascript">…</script>.

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.jscould be implemented like this:

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