我想在 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()
来完成测试,您将在 GeneratorService
实例中的“done”事件的事件监听器中执行此操作。
这是一个例子:
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() - 现在).should.be.at.least(2000)
.
关于javascript - 如何测试函数在一段时间后是否发出事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53560504/