Writing Tests
There are multiple flavors of node-addon-api test builds that cover different
build flags defined in napi.h:
- c++ exceptions enabled,
- c++ exceptions disabled,
- c++ exceptions disabled, and
NODE_ADDON_API_ENABLE_MAYBEdefined.
Functions in node-addon-api that call into JavaScript can have different
declared return types to reflect build flavor settings. For example,
Napi::Object::Set returns bool when NODE_ADDON_API_ENABLE_MAYBE
is not defined, and Napi::Maybe<bool> when NODE_ADDON_API_ENABLE_MAYBE
is defined. In source code, return type variants are defined as
Napi::MaybeOrValue<> to prevent the duplication of most of the code base.
To properly test these build flavors, all values returned by a function defined
to return Napi::MaybeOrValue<> should be tested by using one of the following
test helpers to handle possible JavaScript exceptions.
There are three test helper functions to conveniently convert
Napi::MaybeOrValue<> values to raw values.
MaybeUnwrap
template <typename T> T MaybeUnwrap(MaybeOrValue<T> maybe);
Converts MaybeOrValue<T> to T by checking that MaybeOrValue is NOT an
empty Maybe.
Returns the original value if NODE_ADDON_API_ENABLE_MAYBE is not defined.
Example: