Skip to content

Commit 23802a8

Browse files
committed
Add tests for accessing host from function callbacks
1 parent 4cbf27b commit 23802a8

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

packages/weak-node-api/tests/test_inject.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,42 @@ TEST_CASE("inject_weak_node_api_host") {
2323
REQUIRE(called);
2424
}
2525
}
26+
27+
TEST_CASE("calling into host from functions") {
28+
auto my_create_function = [](napi_env arg0, const char *arg1, size_t arg2,
29+
napi_callback arg3, void *arg4,
30+
napi_value *arg5) -> napi_status {
31+
// This is a failing noop as we're not actually creating a JS functions
32+
return napi_status::napi_generic_failure;
33+
};
34+
NodeApiHost host{.napi_create_function = my_create_function};
35+
inject_weak_node_api_host(host);
36+
napi_env raw_env{};
37+
38+
SECTION("directly") {
39+
napi_value result;
40+
napi_callback cb = [](napi_env env, napi_callback_info info) -> napi_value {
41+
napi_value obj;
42+
napi_status status = napi_create_object(env, &obj);
43+
return obj;
44+
};
45+
46+
napi_create_function(raw_env, "foo", 3, cb, nullptr, &result);
47+
}
48+
49+
SECTION("via callback info") {
50+
napi_value result;
51+
napi_callback cb = [](napi_env env, napi_callback_info info) -> napi_value {
52+
// Get host via callback info
53+
void *data;
54+
napi_get_cb_info(env, info, nullptr, nullptr, nullptr, &data);
55+
auto *host_ptr = static_cast<decltype(&host)>(data);
56+
57+
napi_value obj;
58+
napi_status status = host_ptr->napi_create_object(env, &obj);
59+
return obj;
60+
};
61+
62+
napi_create_function(raw_env, "foo", 3, cb, &host, &result);
63+
}
64+
}

0 commit comments

Comments
 (0)