test(reactivity): improve built-in Collection subclass test cases (#1885)

This commit is contained in:
Pick 2020-08-20 04:22:31 +08:00 committed by GitHub
parent eb2ae44d94
commit 02dcc68c24
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,6 +1,7 @@
import { ref, isRef } from '../src/ref' import { ref, isRef } from '../src/ref'
import { reactive, isReactive, toRaw, markRaw } from '../src/reactive' import { reactive, isReactive, toRaw, markRaw } from '../src/reactive'
import { computed } from '../src/computed' import { computed } from '../src/computed'
import { effect } from '../src/effect'
describe('reactivity/reactive', () => { describe('reactivity/reactive', () => {
test('Object', () => { test('Object', () => {
@ -44,22 +45,59 @@ describe('reactivity/reactive', () => {
expect(isReactive(observed.array[0])).toBe(true) expect(isReactive(observed.array[0])).toBe(true)
}) })
test('process subtypes of collections properly', () => { test('observing subtypes of IterableCollections(Map, Set)', () => {
class CustomMap extends Map { // subtypes of Map
count = 0 class CustomMap extends Map {}
const cmap = reactive(new CustomMap())
set(key: any, value: any): this { expect(cmap instanceof Map).toBe(true)
super.set(key, value) expect(isReactive(cmap)).toBe(true)
this.count++
return this
}
}
const testMap = new CustomMap() cmap.set('key', {})
const observed = reactive(testMap) expect(isReactive(cmap.get('key'))).toBe(true)
expect(observed.count).toBe(0)
observed.set('test', 'value') // subtypes of Set
expect(observed.count).toBe(1) class CustomSet extends Set {}
const cset = reactive(new CustomSet())
expect(cset instanceof Set).toBe(true)
expect(isReactive(cset)).toBe(true)
let dummy
effect(() => (dummy = cset.has('value')))
expect(dummy).toBe(false)
cset.add('value')
expect(dummy).toBe(true)
cset.delete('value')
expect(dummy).toBe(false)
})
test('observing subtypes of WeakCollections(WeakMap, WeakSet)', () => {
// subtypes of WeakMap
class CustomMap extends WeakMap {}
const cmap = reactive(new CustomMap())
expect(cmap instanceof WeakMap).toBe(true)
expect(isReactive(cmap)).toBe(true)
const key = {}
cmap.set(key, {})
expect(isReactive(cmap.get(key))).toBe(true)
// subtypes of WeakSet
class CustomSet extends WeakSet {}
const cset = reactive(new CustomSet())
expect(cset instanceof WeakSet).toBe(true)
expect(isReactive(cset)).toBe(true)
let dummy
effect(() => (dummy = cset.has(key)))
expect(dummy).toBe(false)
cset.add(key)
expect(dummy).toBe(true)
cset.delete(key)
expect(dummy).toBe(false)
}) })
test('observed value should proxy mutations to original (Object)', () => { test('observed value should proxy mutations to original (Object)', () => {