Global `before` and `beforeEach` for mocha?

后端 未结 5 977
长情又很酷
长情又很酷 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 01:00

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

    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 , or better, as an external JS file):

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

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

提交回复
热议问题