test(napi): add JsTimeout specs

This commit is contained in:
LongYinan 2020-10-03 14:57:19 +08:00
parent 43c01796eb
commit e713d647f5
No known key found for this signature in database
GPG key ID: C3666B7FC82ADAD7
2 changed files with 19 additions and 2 deletions

View file

@ -7,11 +7,21 @@ function wait(delay: number) {
return new Promise((resolve) => setTimeout(resolve, delay))
}
const delay = 100
test('should setTimeout', async (t) => {
const handler = Sinon.spy()
const delay = 100
bindings.setTimeout(handler, delay)
t.is(handler.callCount, 0)
await wait(delay + 10)
t.is(handler.callCount, 1)
})
test('should clearTimeout', async (t) => {
const handler = Sinon.spy()
const timer = setTimeout(() => handler(), delay)
t.is(handler.callCount, 0)
bindings.clearTimeout(timer)
await wait(delay + 10)
t.is(handler.callCount, 0)
})

View file

@ -1,6 +1,6 @@
use std::convert::TryInto;
use napi::{CallContext, JsFunction, JsNumber, JsTimeout, Module, Result};
use napi::{CallContext, JsFunction, JsNumber, JsTimeout, JsUndefined, Module, Result};
#[js_function(2)]
pub fn set_timeout(ctx: CallContext) -> Result<JsTimeout> {
@ -12,7 +12,14 @@ pub fn set_timeout(ctx: CallContext) -> Result<JsTimeout> {
.set_timeout(handler, timeout.try_into()?)
}
#[js_function(1)]
pub fn clear_timeout(ctx: CallContext) -> Result<JsUndefined> {
let timer: JsTimeout = ctx.get(0)?;
ctx.env.get_global()?.clear_timeout(timer)
}
pub fn register_js(module: &mut Module) -> Result<()> {
module.create_named_method("setTimeout", set_timeout)?;
module.create_named_method("clearTimeout", clear_timeout)?;
Ok(())
}