index.js 2.2 KB

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