Running a set of actions before every test-file in mocha

前端 未结 2 1804
我寻月下人不归
我寻月下人不归 2021-02-19 02:34

I\'ve started recently working with mocha to test my expressjs server. My tests are separated to multiple files and most of them contain some duplicated segments (Mostly before

相关标签:
2条回答
  • 2021-02-19 03:11

    Why not mocha -r <module> or even using mocha.opts?

    Have your common file in, say, init.js and then run

    mocha -r `./init`
    

    Which will cause mocha to run and load ./init.js before loading any of the mocha test files.

    You could also put it in mocha.opts inside your tests directory, and have its contents be

    --require ./init
    
    0 讨论(0)
  • 2021-02-19 03:34

    There are three basic levels of factoring out common functionality for mocha tests. If you want to load in some fixtures once for a bunch of tests (and you've written each test to be independent), use the before function to load the fixtures at the top of the file. You can also use beforeEach function if you need the fixtures re-initialized each time.

    The second option (which is related), is to pull out common functionality into a separate file or set of files and require that file.

    Finally, note that mocha has a root level hook:

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

    We use that to start an Express server once (and we use an environment variable so that it runs on a different port than our development server):

    before(function () {
      process.env.NODE_ENV = 'test';
      require('../../app.js');
    });
    

    (We don't need a done() here because require is synchronous.) This was, the server is started exactly once, no matter how many different test files include this root-level before function.

    The advantage of splitting things up in this way is that we can run npm test which runs all tests, or run mocha on any specific file or any specific folder, or any specific test or set of tests (using it.only and describe.only) and all of the prerequisites for the selected tests will run.

    0 讨论(0)
提交回复
热议问题