如何检测所有测试(在多个文件中)完成

How to detect all tests (in multiple files) finished

我想在对所有文件进行所有测试后删除数据库 运行。摩卡有挂钩吗?

after() hook 只能在 1 个文件中应用。

我正在使用 process.on('exit')。它在 运行 只有一个文件以及 运行 从 package.json 测试时有效。

database.mocha-base.js:

db.connect()

process.on('exit', async () => {
  console.log('All tests finished. Droping database')
  db.dropDatabase(dbName)
  db.disconnect()
})

module.exports = {
  applyHooks() {
     before(async () => {
        // truncate tables
     })
  }
}

我将 database.mocha-base.js 包括在所有需要数据库访问的测试中:

const dbMochaBase = require('./path/to/database.mocha-base.js')

describe('Tests', () => {
   dbMochaBase.applyHooks()

   ...
})

创建一个 includes/requires 所有其他测试的父文件,然后在该文件中使用 after

describe('User', () => {
  require('../user/user.spec.js')
})

describe('Post', () => {
  require('../post/post.spec.js')
})

describe('Tag', () => {
  require('../tag/tag.spec.js')
})

describe('Routes', () => {
  require('./routes.spec.js')
})

after(() => {
  // drop database
})

mocha 中有一个根级挂钩。对于您的情况,您可以创建一个新文件并在 after 函数中指定 drop database 命令。就是这样!

// init-test.js

after(function() {
  // drop database
});

您无需为该解决方案移动其他测试文件中的任何测试。

参考: https://mochajs.org/#root-level-hooks