From 657476dcdb964be4fbb1277c215c073f3275728e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=AD=8F?= <2553241022@qq.com> Date: Thu, 9 Nov 2023 17:32:21 +0800 Subject: [PATCH] fix(reactivity): clear method on readonly collections should return undefined (#7316) --- packages/reactivity/__tests__/readonly.spec.ts | 16 ++++++++++++++++ .../reactivity/__tests__/shallowReadonly.spec.ts | 12 ++++++++++++ packages/reactivity/src/collectionHandlers.ts | 6 +++++- 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/packages/reactivity/__tests__/readonly.spec.ts b/packages/reactivity/__tests__/readonly.spec.ts index d0c91f0fb9f..448419d3176 100644 --- a/packages/reactivity/__tests__/readonly.spec.ts +++ b/packages/reactivity/__tests__/readonly.spec.ts @@ -275,6 +275,14 @@ describe('reactivity/readonly', () => { expect(isReactive(value)).toBe(true) } }) + + test('should return undefined from Map.clear() call', () => { + const wrapped = readonly(new Collection()) + expect(wrapped.clear()).toBeUndefined() + expect( + `Clear operation failed: target is readonly.` + ).toHaveBeenWarned() + }) } }) }) @@ -332,6 +340,14 @@ describe('reactivity/readonly', () => { expect(isReadonly(v2)).toBe(true) } }) + + test('should return undefined from Set.clear() call', () => { + const wrapped = readonly(new Collection()) + expect(wrapped.clear()).toBeUndefined() + expect( + `Clear operation failed: target is readonly.` + ).toHaveBeenWarned() + }) } }) }) diff --git a/packages/reactivity/__tests__/shallowReadonly.spec.ts b/packages/reactivity/__tests__/shallowReadonly.spec.ts index 79d4376cc01..b6736f4a595 100644 --- a/packages/reactivity/__tests__/shallowReadonly.spec.ts +++ b/packages/reactivity/__tests__/shallowReadonly.spec.ts @@ -113,6 +113,12 @@ describe('reactivity/shallowReadonly', () => { ).not.toHaveBeenWarned() }) }) + + test('should return undefined from Map.clear() call', () => { + const sroMap = shallowReadonly(new Map()) + expect(sroMap.clear()).toBeUndefined() + expect(`Clear operation failed: target is readonly.`).toHaveBeenWarned() + }) }) describe('collection/Set', () => { @@ -197,5 +203,11 @@ describe('reactivity/shallowReadonly', () => { ).not.toHaveBeenWarned() }) }) + + test('should return undefined from Set.clear() call', () => { + const sroSet = shallowReadonly(new Set()) + expect(sroSet.clear()).toBeUndefined() + expect(`Clear operation failed: target is readonly.`).toHaveBeenWarned() + }) }) }) diff --git a/packages/reactivity/src/collectionHandlers.ts b/packages/reactivity/src/collectionHandlers.ts index 1d07af3be8c..fe7d13d1841 100644 --- a/packages/reactivity/src/collectionHandlers.ts +++ b/packages/reactivity/src/collectionHandlers.ts @@ -223,7 +223,11 @@ function createReadonlyMethod(type: TriggerOpTypes): Function { toRaw(this) ) } - return type === TriggerOpTypes.DELETE ? false : this + return type === TriggerOpTypes.DELETE + ? false + : type === TriggerOpTypes.CLEAR + ? undefined + : this } }