null-or-undefined-access.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. test("null/undefined object", () => {
  2. [null, undefined].forEach(value => {
  3. let foo = value;
  4. expect(() => {
  5. foo.bar;
  6. }).toThrowWithMessage(TypeError, `Cannot access property "bar" on ${value} object "foo"`);
  7. expect(() => {
  8. foo.bar = 1;
  9. }).toThrowWithMessage(TypeError, `Cannot access property "bar" on ${value} object "foo"`);
  10. expect(() => {
  11. foo[0];
  12. }).toThrowWithMessage(TypeError, `Cannot access property "0" on ${value} object "foo"`);
  13. expect(() => {
  14. foo[0] = 1;
  15. }).toThrowWithMessage(TypeError, `Cannot access property "0" on ${value} object "foo"`);
  16. });
  17. });
  18. test("null/undefined object key", () => {
  19. [null, undefined].forEach(value => {
  20. let foo = { bar: value };
  21. expect(() => {
  22. foo.bar.baz;
  23. }).toThrowWithMessage(
  24. TypeError,
  25. `Cannot access property "baz" on ${value} object "foo.bar"`
  26. );
  27. expect(() => {
  28. foo.bar.baz = 1;
  29. }).toThrowWithMessage(
  30. TypeError,
  31. `Cannot access property "baz" on ${value} object "foo.bar"`
  32. );
  33. expect(() => {
  34. foo["bar"].baz;
  35. }).toThrowWithMessage(
  36. TypeError,
  37. `Cannot access property "baz" on ${value} object "foo['bar']"`
  38. );
  39. expect(() => {
  40. foo["bar"].baz = 1;
  41. }).toThrowWithMessage(
  42. TypeError,
  43. `Cannot access property "baz" on ${value} object "foo['bar']"`
  44. );
  45. });
  46. });
  47. test("null/undefined array index", () => {
  48. [null, undefined].forEach(value => {
  49. let foo = [value];
  50. let index = 0;
  51. expect(() => {
  52. foo[0].bar;
  53. }).toThrowWithMessage(
  54. TypeError,
  55. `Cannot access property "bar" on ${value} object "foo[0]"`
  56. );
  57. expect(() => {
  58. foo[0].bar = 1;
  59. }).toThrowWithMessage(
  60. TypeError,
  61. `Cannot access property "bar" on ${value} object "foo[0]"`
  62. );
  63. expect(() => {
  64. foo[index].bar;
  65. }).toThrowWithMessage(
  66. TypeError,
  67. `Cannot access property "bar" on ${value} object "foo[index]"`
  68. );
  69. expect(() => {
  70. foo[index].bar = 1;
  71. }).toThrowWithMessage(
  72. TypeError,
  73. `Cannot access property "bar" on ${value} object "foo[index]"`
  74. );
  75. });
  76. });