Skip to content

Commit

Permalink
dx: improve errors for read-only array mutations (#63)
Browse files Browse the repository at this point in the history
  • Loading branch information
divmain committed Jul 26, 2021
1 parent a91008e commit 415b2bd
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/read-only-handler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { unwrap, isUndefined } from './shared';
import { unwrap, isArray, isUndefined } from './shared';
import { BaseProxyHandler, ReactiveMembraneShadowTarget } from './base-handler';

const getterMap = new WeakMap<() => any, () => any>();
Expand Down 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 = 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 415b2bd

Please sign in to comment.