1 | 'use strict';
|
---|
2 |
|
---|
3 | var test = require('tape');
|
---|
4 | var hasSymbols = require('has-symbols/shams')();
|
---|
5 | var hasPropertyDescriptors = require('has-property-descriptors')();
|
---|
6 |
|
---|
7 | var ownKeys = require('../');
|
---|
8 |
|
---|
9 | /** @type {(a: PropertyKey, b: PropertyKey) => number} */
|
---|
10 | function comparator(a, b) {
|
---|
11 | if (typeof a === 'string' && typeof b === 'string') {
|
---|
12 | return a.localeCompare(b);
|
---|
13 | }
|
---|
14 | if (typeof a === 'number' && typeof b === 'number') {
|
---|
15 | return a - b;
|
---|
16 | }
|
---|
17 | return typeof a === 'symbol' ? 1 : -1;
|
---|
18 | }
|
---|
19 |
|
---|
20 | test('ownKeys', function (t) {
|
---|
21 | t.equal(typeof ownKeys, 'function', 'is a function');
|
---|
22 | t.equal(
|
---|
23 | ownKeys.length,
|
---|
24 | 1,
|
---|
25 | 'has a length of 1'
|
---|
26 | );
|
---|
27 |
|
---|
28 | t.test('basics', function (st) {
|
---|
29 | var obj = { a: 1, b: 2 };
|
---|
30 | if (hasPropertyDescriptors) {
|
---|
31 | Object.defineProperty(obj, 'c', {
|
---|
32 | configurable: true,
|
---|
33 | enumerable: false,
|
---|
34 | writable: true,
|
---|
35 | value: 3
|
---|
36 | });
|
---|
37 | }
|
---|
38 |
|
---|
39 | st.deepEqual(
|
---|
40 | ownKeys(obj).sort(comparator),
|
---|
41 | (hasPropertyDescriptors ? ['a', 'b', 'c'] : ['a', 'b']).sort(comparator),
|
---|
42 | 'includes non-enumerable properties'
|
---|
43 | );
|
---|
44 |
|
---|
45 | st.end();
|
---|
46 | });
|
---|
47 |
|
---|
48 | t.test('symbols', { skip: !hasSymbols }, function (st) {
|
---|
49 | /** @type {Record<PropertyKey, unknown>} */
|
---|
50 | var obj = { a: 1 };
|
---|
51 | var sym = Symbol('b');
|
---|
52 | obj[sym] = 2;
|
---|
53 |
|
---|
54 | var nonEnumSym = Symbol('c');
|
---|
55 | Object.defineProperty(obj, nonEnumSym, {
|
---|
56 | configurable: true,
|
---|
57 | enumerable: false,
|
---|
58 | writable: true,
|
---|
59 | value: 3
|
---|
60 | });
|
---|
61 |
|
---|
62 | st.deepEqual(
|
---|
63 | ownKeys(obj).sort(comparator),
|
---|
64 | ['a', sym, nonEnumSym].sort(comparator),
|
---|
65 | 'works with symbols, both enum and non-enum'
|
---|
66 | );
|
---|
67 |
|
---|
68 | st.end();
|
---|
69 | });
|
---|
70 |
|
---|
71 | t.end();
|
---|
72 | });
|
---|