ladybird/Userland/Libraries/LibJS/Tests/null-or-undefined-access.js
Timothy Flynn 22fdcfbc50 LibJS: Include identifier information in nullish property write access
When a PutById / PutByValue 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 = 1
  Uncaught exception:
  [TypeError] Cannot access property "bar" on null object "foo"
      at <unknown>

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

Note we certainly don't capture all possible nullish property write
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

55 lines
1.6 KiB
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.bar = 1;
}).toThrowWithMessage(TypeError, `Cannot access property "bar" on ${value} object "foo"`);
expect(() => {
foo[0];
}).toThrowWithMessage(TypeError, `Cannot access property "0" on ${value} object "foo"`);
expect(() => {
foo[0] = 1;
}).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"`
);
expect(() => {
foo.bar.baz = 1;
}).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`);
expect(() => {
foo[0].bar = 1;
}).toThrowWithMessage(TypeError, `Cannot access property "bar" on ${value} object`);
});
});