【问题标题】:How to test does function emits event after some time?如何测试函数是否在一段时间后发出事件?
【发布时间】:2019-05-02 18:49:38
【问题描述】:

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

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 秒后发出。

【问题讨论】:

标签: javascript node.js mocha.js bdd chai


【解决方案1】:

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

通过这种方式,您向 Mocha 发出这是一个 async test 的信号,并且您希望等到您调用 done() 来完成测试,您将在事件侦听器中为您的 @ 中的“完成”事件执行此操作987654325@实例。

这是一个例子:

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()
  })
})

注意:我将 GeneratorService 替换为 Client,并使其更简洁。

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

【讨论】:

  • 谢谢。这是我的第一个 mocha/chai 项目,我知道这是谁的问题。为什么将err 传递给done()?它给了我错误 bcz err is undefined = Error: done() invoked with non-Error: value
  • 已修改;您应该调用done(err),并使用err 参数类型为Error,以防您想向mocha 发出信号,表明您想以错误结束此测试(它失败了)。否则只需done()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
  • 2019-04-22
  • 2016-08-21
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
相关资源
最近更新 更多