Skip to content

Commit 0213134

Browse files
JckXiamhdawson
authored andcommitted
test: add unit test covg for callbackscopes
PR-URL: #1262 Reviewed-By: Michael Dawson <[email protected]
1 parent b11e4de commit 0213134

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

test/callbackscope.cc

+19-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1+
#include "assert.h"
12
#include "napi.h"
2-
33
using namespace Napi;
44

55
#if (NAPI_VERSION > 2)
6+
67
namespace {
78

89
static void RunInCallbackScope(const CallbackInfo& info) {
@@ -12,11 +13,27 @@ static void RunInCallbackScope(const CallbackInfo& info) {
1213
callback.Call({});
1314
}
1415

15-
} // end anonymous namespace
16+
static void RunInCallbackScopeFromExisting(const CallbackInfo& info) {
17+
Function callback = info[0].As<Function>();
18+
Env env = info.Env();
19+
20+
AsyncContext ctx(env, "existing_callback_scope_test");
21+
napi_callback_scope scope;
22+
napi_open_callback_scope(env, Object::New(env), ctx, &scope);
23+
24+
CallbackScope existingScope(env, scope);
25+
assert(existingScope.Env() == env);
26+
27+
callback.Call({});
28+
}
29+
30+
} // namespace
1631

1732
Object InitCallbackScope(Env env) {
1833
Object exports = Object::New(env);
1934
exports["runInCallbackScope"] = Function::New(env, RunInCallbackScope);
35+
exports["runInPreExistingCbScope"] =
36+
Function::New(env, RunInCallbackScopeFromExisting);
2037
return exports;
2138
}
2239
#endif

test/callbackscope.js

+6-3
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ function test (binding) {
2424
let insideHook = false;
2525
const hook = asyncHooks.createHook({
2626
init (asyncId, type, triggerAsyncId, resource) {
27-
if (id === undefined && type === 'callback_scope_test') {
27+
if (id === undefined && (type === 'callback_scope_test' || type === 'existing_callback_scope_test')) {
2828
id = asyncId;
2929
}
3030
},
@@ -39,8 +39,11 @@ function test (binding) {
3939
return new Promise(resolve => {
4040
binding.callbackscope.runInCallbackScope(function () {
4141
assert(insideHook);
42-
hook.disable();
43-
resolve();
42+
binding.callbackscope.runInPreExistingCbScope(function () {
43+
assert(insideHook);
44+
hook.disable();
45+
resolve();
46+
});
4447
});
4548
});
4649
}

0 commit comments

Comments
 (0)