首页 > 解决方案 > 运行具有相同上下文的多个 mocha 文件和套件

问题描述

我正在尝试使用一些共享上下文运行几个集成测试。共享的上下文是一个单一的快速应用程序,我试图在套件/文件之间共享它,因为它需要几秒钟才能启动。

我通过实例化一个“运行器”mocha 测试套件来使其工作,该套件将具有测试功能,可以require根据需要仅对每个测试文件进行测试,并且效果很好(副作用是需要子测试文件的测试将完成为在文件中的任何测试实际运行之前“成功”,但这是一个小问题)

// test-runner.js:

describe('Integration tests', function () {
  let app
  let log
  this.timeout(300000) // 5 mins
  before(function (done) {

    app = require('../app')
    app.initialize()
      .then(() => {
        done()
      })
      .catch(err => {
        log.error(err)
        done(err)
      })
  })

  it('Running api tests...', (done) => {
    require('./integration/api.test')(app)
    done()
  })
// ./integration/api.test.js:

module.exports = (app) => {
  let api = supertest.agent(app)
      .set('Content-Type', 'application/json')

  describe('Authorization', () => {
    describe('Trying to access authorization sections', () => {
      it('should be denied for /home', async () => {
        await api.get(`${baseUrl}/home`)
          .expect(STATUS_CODE.UNAUTHORIZED)
      })
...

问题:

我想通知测试运行程序导入套件中的所有测试都已完成,因此我可以在测试运行程序中调用关闭逻辑并干净地结束测试。在标准测试函数中,您可以传递一个done函数来表示测试中的代码已完成,因此我将每个子测试包装在一个描述块中,以使用after钩子来表示整个测试模块已完成:

// test-runner.js:

describe('Integration tests', function () {
  let app
  let log
  this.timeout(300000) // 5 mins
  before(function (done) {

    app = require('../app')
    app.initialize()
      .then(() => {
        done()
      })
      .catch(err => {
        log.error(err)
        done(err)
      })
  })

  it('Running api tests...', (done) => {
    require('./integration/api.test')(app, done)
  })
// ./integration/api.test.js:

module.exports = (app, done) => {
  let api = supertest.agent(app)
      .set('Content-Type', 'application/json')

  describe('All api tests', () => {
    let api
    before(() => {
      api = supertest.agent(app)
        .set('Content-Type', 'application/json')
    })
    after(() => {
      done()  // should be calling the done function passed in by test runner
    })
    describe('Authorization', () => {
      describe('Trying to access authorization sections', () => {
        it('should be denied for /home', async () => {
          await api.get(`${baseUrl}/home`)
            .expect(STATUS_CODE.UNAUTHORIZED)
        })
...

但是当我这样做时,测试套件就不会运行。默认超时将过期,如果我设置了更高的超时,它只是坐在那里(等待更长的超时)。如果我挂钩到调试会话,那么测试会立即退出,并且后挂钩(和之前!)永远不会被调用。

我也对如何做到这一点持开放态度,但我还没有找到任何好的解决方案,可以在测试之间共享一些上下文,同时将它们分成不同的文件。

标签: node.jsautomated-testsmocha.jsintegration-testing

解决方案


推荐阅读