我想在Chai测试一段时间后是否发出了某些事件。 我的课:
export default class GeneratorService {
constructor() {
this.evn = new Events();
this.generate();
}
generate() {
this.check();
}
check() {
setTimeout(() => {
this.evn.events.emit('done', 'value');
}, 2000);
}
}
我不知道如何在2秒后发出事件done
。
答案 0 :(得分:2)
通过将 one 参数传递给IntegrityError
(通常称为it
),然后
然后在您想完成测试时调用该参数。
通过这种方式,您向Mocha发出信号,表明这是async test,并且您要等到调用done
才能完成测试,然后在事件监听器中对“完成”进行操作您的done()
实例中的事件。
这是一个例子:
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()
})
})
替换了GeneratorService
。
此外,您可能可以使用Mocha的默认2000ms超时限制来检查事件是否确实在2秒内触发,从而无需添加我在示例中添加的时间比较:Client