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

Viewed 269

I am reading the following book Testing Vue js application

the code

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

the test

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");
  })   

The test must be passed according to the book but in my case, it does not and I get the following error

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 |   })

but when I nextTick like the following the test passes

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

The only explanation I can find is

nextTick is used cuz the dom update is happing async

Could anyone give me a better explanation?

Does it mean the book material is deprecated?

3 Answers

I was reading that book recently. I was writing tests a lot and found out that trick with nextTick is not working for me. In cases when I want to be sure that changes I made to DOM were applied I use async/await. There is my version of your test:

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')
  })

About the book: the book is great actually. I could not find more detailed explanation on testing Vue apps in the Internet. Book helped a lot.

That's actually an accurate explanation.

However, perhaps the docs provide some more clarity:

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.

The issue here is with version dependencies. Each chapter in this book seems to have its own dependencies and versions. If you are going from chapter to chapter, you are probably not rebuilding your node_moduels with every git checkout.

Related