Skip to content

Commit

Permalink
dx: improve errors for read-only array mutations
Browse files Browse the repository at this point in the history
  • Loading branch information
divmain committed Jul 22, 2021
1 parent a91008e commit cb9fcce
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/read-only-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ export class ReadOnlyHandler extends BaseProxyHandler {
set(shadowTarget: ReactiveMembraneShadowTarget, key: PropertyKey, value: any): boolean {
if (process.env.NODE_ENV !== 'production') {
const { originalTarget } = this;
throw new Error(`Invalid mutation: Cannot set "${key.toString()}" on "${originalTarget}". "${originalTarget}" is read-only.`);
const msg = Array.isArray(originalTarget) ?
`Invalid mutation: Cannot mutate array at index ${key.toString()}. Array is read-only.` :
`Invalid mutation: Cannot set "${key.toString()}" on "${originalTarget}". "${originalTarget}" is read-only.`;
throw new Error(msg);
}
return false;
}
Expand Down
10 changes: 10 additions & 0 deletions test/read-only-handler.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -425,4 +425,14 @@ describe('ReadOnlyHandler', () => {
expect(wet.foo).toBe(1);
});
});
it("should throw a helpful message when attempting to mutate an array", function () {
const target = new ReactiveMembrane();
const obj = [];
const property = target.getReadOnlyProxy(obj);
expect(() => {
property.push("some object");
}).toThrowErrorMatchingInlineSnapshot(
`"Invalid mutation: Cannot mutate array at index 0. Array is read-only."`
);
});
});

0 comments on commit cb9fcce

Please sign in to comment.