• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../../common');
3const assert = require('assert');
4
5const getterOnlyErrorRE =
6  /^TypeError: Cannot set property .* of #<.*> which has only a getter$/;
7
8// Testing api calls for a constructor that defines properties
9const TestConstructor = require(`./build/${common.buildType}/test_constructor`);
10const test_object = new TestConstructor();
11
12assert.strictEqual(test_object.echo('hello'), 'hello');
13
14test_object.readwriteValue = 1;
15assert.strictEqual(test_object.readwriteValue, 1);
16test_object.readwriteValue = 2;
17assert.strictEqual(test_object.readwriteValue, 2);
18
19assert.throws(() => { test_object.readonlyValue = 3; },
20              /^TypeError: Cannot assign to read only property 'readonlyValue' of object '#<MyObject>'$/);
21
22assert.ok(test_object.hiddenValue);
23
24// Properties with napi_enumerable attribute should be enumerable.
25const propertyNames = [];
26for (const name in test_object) {
27  propertyNames.push(name);
28}
29assert.ok(propertyNames.includes('echo'));
30assert.ok(propertyNames.includes('readwriteValue'));
31assert.ok(propertyNames.includes('readonlyValue'));
32assert.ok(!propertyNames.includes('hiddenValue'));
33assert.ok(!propertyNames.includes('readwriteAccessor1'));
34assert.ok(!propertyNames.includes('readwriteAccessor2'));
35assert.ok(!propertyNames.includes('readonlyAccessor1'));
36assert.ok(!propertyNames.includes('readonlyAccessor2'));
37
38// The napi_writable attribute should be ignored for accessors.
39test_object.readwriteAccessor1 = 1;
40assert.strictEqual(test_object.readwriteAccessor1, 1);
41assert.strictEqual(test_object.readonlyAccessor1, 1);
42assert.throws(() => { test_object.readonlyAccessor1 = 3; }, getterOnlyErrorRE);
43test_object.readwriteAccessor2 = 2;
44assert.strictEqual(test_object.readwriteAccessor2, 2);
45assert.strictEqual(test_object.readonlyAccessor2, 2);
46assert.throws(() => { test_object.readonlyAccessor2 = 3; }, getterOnlyErrorRE);
47
48// Validate that static properties are on the class as opposed
49// to the instance
50assert.strictEqual(TestConstructor.staticReadonlyAccessor1, 10);
51assert.strictEqual(test_object.staticReadonlyAccessor1, undefined);
52
53// Verify that passing NULL to napi_define_class() results in the correct
54// error.
55assert.deepStrictEqual(TestConstructor.TestDefineClass(), {
56  envIsNull: 'Invalid argument',
57  nameIsNull: 'Invalid argument',
58  cbIsNull: 'Invalid argument',
59  cbDataIsNull: 'napi_ok',
60  propertiesIsNull: 'Invalid argument',
61  resultIsNull: 'Invalid argument',
62});
63