ladybird/Userland/Libraries/LibJS/Tests/null-or-undefined-access.js
Timothy Flynn 9bbd3103a8 LibJS: Include identifier information in nullish property read access
When a GetById / GetByValue bytecode operation results in accessing a
nullish object, we now include the name of the property and the object
being accessed in the exception message (if available). This should make
it easier to debug live websites.

For example, the following errors would all previously produce a generic
error message of "ToObject on null or undefined":

  > foo = null
  > foo.bar
  Uncaught exception:
  [TypeError] Cannot access property "bar" on null object "foo"
      at <unknown>

  > foo = { bar: undefined }
  > foo.bar.baz
  Uncaught exception:
  [TypeError] Cannot access property "baz" on undefined object "foo.bar"
      at <unknown>

Note we certainly don't capture all possible nullish property read
accesses here. This just covers cases I've seen most on live websites;
we can cover more cases as they arise.
2024-03-29 21:57:19 +01:00

36 lines
982 B
JavaScript

test("null/undefined object", () => {
[null, undefined].forEach(value => {
let foo = value;
expect(() => {
foo.bar;
}).toThrowWithMessage(TypeError, `Cannot access property "bar" on ${value} object "foo"`);
expect(() => {
foo[0];
}).toThrowWithMessage(TypeError, `Cannot access property "0" on ${value} object "foo"`);
});
});
test("null/undefined object key", () => {
[null, undefined].forEach(value => {
let foo = { bar: value };
expect(() => {
foo.bar.baz;
}).toThrowWithMessage(
TypeError,
`Cannot access property "baz" on ${value} object "foo.bar"`
);
});
});
test("null/undefined array index", () => {
[null, undefined].forEach(value => {
let foo = [value];
expect(() => {
foo[0].bar;
}).toThrowWithMessage(TypeError, `Cannot access property "bar" on ${value} object`);
});
});