调用方法不改变DOM 属性值(Vue Jest testing-vue-js-applications book)

Calling method does not change DOM property value (Vue Jest testing-vue-js-applications book)

我正在阅读以下书籍 Testing Vue js application

代码

<template>
  <div
    :class="{ hidden: isHidden}"
    :style="{
      width: '0%',
    }"
  />
</template>
<script>
export default {
  data() {
    return {
      isHidden: true,
    }
  },
  methods: {
    start() {
      this.isHidden = false;
    },
    finish() {},
  },
};
</script>

测试

test('displays the bar when start is called', () => {
    const wrapper = mount(ProgressBar)       
    expect(wrapper.classes()).toContain('hidden')         
    wrapper.vm.start()      
    expect(wrapper.classes()).not.toContain("hidden");
  })   

按照书上的测试必须通过,但我没有通过,出现以下错误

expect(array).not.toContain(value)

    Expected array:
      ["hidden"]
    Not to contain value:
      "hidden"

      21 |     // nextTick is used cuz the dom update is happing async
      22 |     // wrapper.vm.$nextTick(() => {
    > 23 |       expect(wrapper.classes()).not.toContain("hidden");
         |                                     ^
      24 |     // });
      25 |  
      26 |   })

但是当我 nextTick 如下所示时,测试通过了

wrapper.vm.$nextTick(() => {
  expect(wrapper.classes()).not.toContain("hidden");
});

我能找到的唯一解释是

nextTick is used cuz the dom update is happing async

谁能给我一个更好的解释?

这是否意味着这本书 material 已被弃用?

这实际上是一个准确的解释。

但是,也许 the docs 更清晰:

In case you haven’t noticed yet, Vue performs DOM updates asynchronously. Whenever a data change is observed, it will open a queue and buffer all the data changes that happen in the same event loop. [...]

For example, when you set vm.someData = 'new value', the component will not re-render immediately. It will update in the next “tick”, when the queue is flushed.

此处的问题与版本依赖性有关。本书的每一章似乎都有自己的依赖关系和版本。如果你要逐章阅读,你可能不会在每个 git checkout.

时重建你的 node_moduels

我最近在看那本书。我写了很多测试,发现 nextTick 的技巧对我不起作用。如果我想确保对 DOM 所做的更改得到应用,我会使用 async/await。这是我的测试版本:

test('displays the bar when start is called', async () => {
    const wrapper = shallowMount(ProgressBar)
    expect(wrapper.classes()).toContain('hidden')   
    await wrapper.vm.start()
    expect(wrapper.classes()).not.toContain('hidden')
  })

关于这本书:这本书其实很棒。我无法在 Internet 上找到有关测试 Vue 应用程序的更详细说明。书帮了大忙。