Skip to content

Watching a computed property depending on a reactive array #6

Open
@Toilal

Description

I wrote this test, which runs when removing the watcher, but fails when it's present.

import { computed, Ref, ref } from '@vue/reactivity'
import { watch } from '@vue-reactivity/watch'
import { fn } from 'jest-mock'
import { any } from 'jest-mock-extended'

it('should watch inside an array ref when an item is removed', () => {
  const rowsData: { p1: Ref<number>, p2: Ref<number>, p3: Ref<number> }[] = []

  for (let i = 0; i < 5; i++) {
    const p1 = ref(1)
    const p2 = ref(2)
    const p3 = ref(3)
    rowsData.push({ p1, p2, p3 })
  }
  const rows = ref(rowsData)

  const c = computed(() => {
    let sum = 0
    for (const row of rows.value) {
      sum += row.p1
      sum += row.p2
      sum += row.p3
    }
    return sum
  })

  const watchFunction = fn()
  watch(c, watchFunction) // When removing this line, the test is OK.

  expect(c.value).toBe(30)
  rows.value.splice(1, 1)
  expect(c.value).toBe(24)

  expect(watchFunction).toBeCalledWith(24, 30, any()) // When removing this line, the test is OK.
})
Cannot read properties of undefined (reading 'p1')
TypeError: Cannot read properties of undefined (reading 'p1')
    at ReactiveEffect.fn (/home/toilal/projects/carbon-saver/platform.carbon-saver/packages/computation-core.carbon-saver/__tests__/reactivity.spec.ts:20:18)
    at ReactiveEffect.run (/home/toilal/projects/carbon-saver/platform.carbon-saver/node_modules/@vue/reactivity/dist/reactivity.cjs.js:189:25)
    at ComputedRefImpl.get value [as value] (/home/toilal/projects/carbon-saver/platform.carbon-saver/node_modules/@vue/reactivity/dist/reactivity.cjs.js:1136:39)
    at ReactiveEffect.getter [as fn] (/home/toilal/projects/carbon-saver/platform.carbon-saver/node_modules/@vue-reactivity/watch/dist/index.js:83:27)
    at ReactiveEffect.run (/home/toilal/projects/carbon-saver/platform.carbon-saver/node_modules/@vue/reactivity/dist/reactivity.cjs.js:189:25)
    at job (/home/toilal/projects/carbon-saver/platform.carbon-saver/node_modules/@vue-reactivity/watch/dist/index.js:129:31)
    at ReactiveEffect.scheduler (/home/toilal/projects/carbon-saver/platform.carbon-saver/node_modules/@vue-reactivity/watch/dist/index.js:150:7)
    at triggerEffect (/home/toilal/projects/carbon-saver/platform.carbon-saver/node_modules/@vue/reactivity/dist/reactivity.cjs.js:393:20)
    at triggerEffects (/home/toilal/projects/carbon-saver/platform.carbon-saver/node_modules/@vue/reactivity/dist/reactivity.cjs.js:383:13)
    at triggerRefValue (/home/toilal/projects/carbon-saver/platform.carbon-saver/node_modules/@vue/reactivity/dist/reactivity.cjs.js:995:13)

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions