为什么我的数组在方法调用 live 时更新但在单元测试中不更新?

Why does my array update when method called live but doesn't in unit tests?

我有一个名为 toggleSelect 的方法,它在名为 selectedItems 的数组中添加和删除对象。这在浏览器中完美运行。 在我的单元测试期间它似乎不起作用。不清楚为什么,因为我直接从组件调用它并向它传递一个参数。如果我 console.log() 方法中的项目,它会正确显示在日志中。方法运行,但数组永远不会更新以验证它是否有效。

let items = [{
  "ID": "12345",
  "Name": "Real Person",
  "Description": "How a real person ought to be described",
  "Date": "2015-04-12T04:24:49-07:00",
  "Amount": 120.23
}]

const wrapper = shallowMount(DataTable, {
  propsData:  { items }
})

// toggle method directly on component
wrapper.vm.toggleSelect(items[0])

// verify that the array has been updated
console.log(DataTable.data().selectedItems)

日志显示刚刚在测试中是一个空数组。

DataTable.data().selectedItems 应该是 wrapper.vm.selectedItems.

组件实例的数据属性也在wrapper.vm上公开,因此您可以直接通过键访问实例的当前数据:

expect(wrapper.vm.selectedItems).toContain(items[0])