Global `before` and `beforeEach` for mocha?

后端 未结 5 973
长情又很酷
长情又很酷 2021-02-01 00:38

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

I have several test files, each file has a before and beforeEach, but they are exactly the s

5条回答
  •  攒了一身酷
    2021-02-01 00:59

    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

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

    '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…


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

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

    ( 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... )

    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…)

提交回复
热议问题