代码之家  ›  专栏  ›  技术社区  ›  Amio.io

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

  •  1
  • Amio.io  · 技术社区  · 7 年前

    我希望在所有文件中的所有测试运行后删除数据库。摩卡有钩子吗?

    after() 钩子只能在1个文件内应用。

    3 回复  |  直到 7 年前
        1
  •  1
  •   deerawan    7 年前

    摩卡有一个根级别的钩子。对于您的案例,您可以创建一个新文件并在中指定drop database命令。 after 功能。就是这样!

    // init-test.js
    
    after(function() {
      // drop database
    });
    

    对于此解决方案,您不需要移动其他测试文件中的任何测试。

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

        2
  •  1
  •   nicholaswmin    7 年前

    创建包含/需要所有其他测试的父文件,然后使用 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
    })
    
        3
  •  0
  •   Amio.io    7 年前

    我在用 process.on('exit') . 当只运行一个文件时,以及在运行测试时, 包装袋 .

    数据库.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()
    
       ...
    })
    
    推荐文章