如何测试函数在一段时间后是否发出事件?

How to test does function emits event after some time?

我想在 Chai 中测试一段时间后是否发出了某些事件。 我的class:

export default class GeneratorService {
  constructor() {
      this.evn = new Events();
      this.generate();
  }

  generate() {
      this.check();
  }

  check() {
      setTimeout(() => {
            this.evn.events.emit('done', 'value');
      }, 2000);
  }

}

我不知道如何测试事件 done 是否在 2 秒后发出。

通过将一个参数传递给it(通常称为done)和 然后在您想完成测试时调用该参数。

通过这种方式,您向 Mocha 发出信号这是一个 async test,并且您想等到调用 done() 完成测试,您将在 done() 的事件侦听器中执行此操作=33=] 来自您的 GeneratorService 实例的事件。

这是一个例子:

const chai = require('chai')
const EventEmitter = require('events').EventEmitter

chai.should()

class Client {
  constructor() {
    this.evt = new EventEmitter()
  }

  fireDone() {
    setTimeout(() => {
      this.evt.emit('done')
    }, 2000)
  }
}

describe('Client', function () {
  // increase mocha's default timeout to 3000ms, otherwise
  // the test will timeout after 2000ms.
  this.timeout(3000)

  const client = new Client()

  it('emits done after 2000 ms', function(done) {
    const now = Date.now()

    client.evt.on('done', function end(value) {
      (Date.now() - now).should.be.at.least(2000)
      // Do more assertions here; perhaps add tests for `value`.          

      // Here we call done, signalling to mocha
      // that this test is finally over.
      done()

      // remove listener so it doesn't re-fire on next test.
      client.evt.removeListener('done', end)
    })

    client.fireDone()
  })
})

注意:我用Client替换了GeneratorService,为了简洁起见使它更紧凑。

此外,您或许可以使用 Mocha 的默认 2000 毫秒超时限制来检查事件是否确实在 2 秒内触发,这样就不需要添加我检查过的时间比较,我已经在我的示例中添加了:(Date.now() - now).should.be.at.least(2000).