index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. 'use strict';
  2. var test = require('tape');
  3. var inspect = require('object-inspect');
  4. var hasBigInts = require('has-bigints')();
  5. var hasSymbols = require('has-symbols')();
  6. var hasToStringTag = require('has-tostringtag/shams')();
  7. var isBigInt = require('../');
  8. var debug = function (v, m) { return inspect(v) + ' ' + m; };
  9. var forEach = function (arr, func) {
  10. var i;
  11. for (i = 0; i < arr.length; ++i) {
  12. func(arr[i], i, arr);
  13. }
  14. };
  15. test('non-BigInt values', function (t) {
  16. var nonBigInts = [
  17. true,
  18. false,
  19. Object(true),
  20. Object(false),
  21. null,
  22. undefined,
  23. {},
  24. [],
  25. /a/g,
  26. 'string',
  27. 42,
  28. new Date(),
  29. function () {},
  30. NaN
  31. ];
  32. if (hasSymbols) {
  33. nonBigInts.push(Symbol.iterator, Symbol('foo'));
  34. }
  35. t.plan(nonBigInts.length);
  36. forEach(nonBigInts, function (nonBigInt) {
  37. t.equal(false, isBigInt(nonBigInt), debug(nonBigInt, 'is not a BigInt'));
  38. });
  39. t.end();
  40. });
  41. test('faked BigInt values', function (t) {
  42. t.test('real BigInt valueOf', { skip: !hasBigInts }, function (st) {
  43. var fakeBigInt = { valueOf: function () { return BigInt(42); } };
  44. st.equal(false, isBigInt(fakeBigInt), 'object with valueOf returning a BigInt is not a BigInt');
  45. st.end();
  46. });
  47. t.test('faked @@toStringTag', { skip: !hasBigInts || !hasToStringTag }, function (st) {
  48. var fakeBigInt = { valueOf: function () { return BigInt(42); } };
  49. fakeBigInt[Symbol.toStringTag] = 'BigInt';
  50. st.equal(false, isBigInt(fakeBigInt), 'object with fake BigInt @@toStringTag and valueOf returning a BigInt is not a BigInt');
  51. var notSoFakeBigInt = { valueOf: function () { return 42; } };
  52. notSoFakeBigInt[Symbol.toStringTag] = 'BigInt';
  53. st.equal(false, isBigInt(notSoFakeBigInt), 'object with fake BigInt @@toStringTag and valueOf not returning a BigInt is not a BigInt');
  54. st.end();
  55. });
  56. var fakeBigIntString = { toString: function () { return '42n'; } };
  57. t.equal(false, isBigInt(fakeBigIntString), 'object with toString returning 42n is not a BigInt');
  58. t.end();
  59. });
  60. test('BigInt support', { skip: !hasBigInts }, function (t) {
  61. forEach([
  62. Function('return 42n')(), // eslint-disable-line no-new-func
  63. BigInt(42),
  64. Object(BigInt(42))
  65. ], function (bigInt) {
  66. t.equal(true, isBigInt(bigInt), debug(bigInt, 'is a BigInt'));
  67. });
  68. t.end();
  69. });