From 021313409e2afb4fc638461fe14021f1b4815537 Mon Sep 17 00:00:00 2001 From: JckXia Date: Fri, 23 Dec 2022 16:24:03 -0500 Subject: [PATCH] test: add unit test covg for callbackscopes PR-URL: https://github.com/nodejs/node-addon-api/pull/1262 Reviewed-By: Michael Dawson 2) + namespace { static void RunInCallbackScope(const CallbackInfo& info) { @@ -12,11 +13,27 @@ static void RunInCallbackScope(const CallbackInfo& info) { callback.Call({}); } -} // end anonymous namespace +static void RunInCallbackScopeFromExisting(const CallbackInfo& info) { + Function callback = info[0].As(); + Env env = info.Env(); + + AsyncContext ctx(env, "existing_callback_scope_test"); + napi_callback_scope scope; + napi_open_callback_scope(env, Object::New(env), ctx, &scope); + + CallbackScope existingScope(env, scope); + assert(existingScope.Env() == env); + + callback.Call({}); +} + +} // namespace Object InitCallbackScope(Env env) { Object exports = Object::New(env); exports["runInCallbackScope"] = Function::New(env, RunInCallbackScope); + exports["runInPreExistingCbScope"] = + Function::New(env, RunInCallbackScopeFromExisting); return exports; } #endif diff --git a/test/callbackscope.js b/test/callbackscope.js index 54a3844df..cafb180ca 100644 --- a/test/callbackscope.js +++ b/test/callbackscope.js @@ -24,7 +24,7 @@ function test (binding) { let insideHook = false; const hook = asyncHooks.createHook({ init (asyncId, type, triggerAsyncId, resource) { - if (id === undefined && type === 'callback_scope_test') { + if (id === undefined && (type === 'callback_scope_test' || type === 'existing_callback_scope_test')) { id = asyncId; } }, @@ -39,8 +39,11 @@ function test (binding) { return new Promise(resolve => { binding.callbackscope.runInCallbackScope(function () { assert(insideHook); - hook.disable(); - resolve(); + binding.callbackscope.runInPreExistingCbScope(function () { + assert(insideHook); + hook.disable(); + resolve(); + }); }); }); }