最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - mocha global `before` that executes only 1 time - Stack Overflow

programmeradmin4浏览0评论

I'm using mocha for node.js functional testing.

There are several files in my test.

How can I run a piece of code for only one time before all tests start?

For example, I may have to set up a docker container before all tests start. Is it possible to do this with mocha?

The before hook runs 1 time for every test file. This doesn't meet my needs.

I'm using mocha for node.js functional testing.

There are several files in my test.

How can I run a piece of code for only one time before all tests start?

For example, I may have to set up a docker container before all tests start. Is it possible to do this with mocha?

The before hook runs 1 time for every test file. This doesn't meet my needs.

Share Improve this question asked Dec 24, 2017 at 7:52 BrianBrian 13.6k22 gold badges105 silver badges182 bronze badges 1
  • The easiest way I have found so far is to create a file with a name starting with underscore, e.g. _before.test.js which will run before the other tests since mocha loads them alphabetically. – Tsvetan Ganev Commented Dec 24, 2017 at 8:26
Add a ment  | 

3 Answers 3

Reset to default 5

You can have 'root' level hooks, if you put them outside of any describe blocks. So you can put your relevant code in any files inside of the test folder.

before(function() {
  console.log('before any tests started');
});

See the docs: http://mochajs/#root-level-hooks

Mocha 8 introduces the concept of root hook plugins. In your case, the relevant ones are beforeAll and afterAll, which will run once before/after all tests, so long you tests run in serial.

You can write:

exports.mochaHooks = {
  beforeAll(done) {
    // do something before all tests run
    done();
  },
};

And you'll have to add this file using the --require flag.

See docs for more info.

There is a very clean solution for this. Use --file as parameter in your mocha mand. It works like a global hook for your tests.

xargs mocha -R spec --file <path-to-setup-file>

A setup file can look like this:

'use strict';
const mongoHelper = require('./mongoHelper.js');

console.log("[INFO]: Starting tests ...");
// connect to database

mongoHelper.connect()
.then(function(connection){
  console.log("[INFO]: Connected to database ...");
  console.log(connection);
})
.catch(function(err){
  console.error("[WARN]: Connection to database failed ...");
  console.log(err);
});

Unfortunately I have not found a way to use async/await in this setup files. So I think you may have to be conent with using "old" promise and callback code.

发布评论

评论列表(0)

  1. 暂无评论