index.js 1.5 KB

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