damontes
damontes

Reputation: 21

Vue Test Utils - data does not update after triggering click event

I have this basic test using Vue Test Utils:

import { mount } from '@vue/test-utils'

const App = {
  template: `
    <p>Count: {{ count }}</p>
    <button @click="handleClick">Increment</button>
  `,
  data() {
    return {
      count: 0
    }
  },
  methods: {
    handleClick() {
      this.count += 1
    }
  }
}

test('it increments by 1', async () => {
  const wrapper = mount(App, {
    data() {
      return {
        count: 0
      }
    }
  })
  expect(wrapper.html()).toContain('Count: 0')
  await wrapper.find('button').trigger('click')
  expect(wrapper.html()).toContain('Count: 1')
})

The test only passes if I either

However, according to the documentation, shouldn't it just pass as it is already written?

Upvotes: 2

Views: 1341

Answers (2)

Ajeesh Sathyan
Ajeesh Sathyan

Reputation: 347

import { mount } from '@vue/test-utils'

const sleep = (ms: number) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

const App = {
  template: `
    <p>Count: {{ count }}</p>
    <button @click="handleClick">Increment</button>
  `,
  data() {
    return {
      count: 0
    }
  },
  methods: {
    handleClick() {
      this.count += 1
    }
  }
}

test('it increments by 1', async () => {
  const wrapper = mount(App, {
    data() {
      return {
        count: 0
      }
    }
  })
  expect(wrapper.html()).toContain('Count: 0')
  await wrapper.find('button').trigger('click')
  await wrapper.vm.$nextTick();
  await sleep(2000);
  expect(wrapper.html()).toContain('Count: 1')
})

Upvotes: 2

mk_xt
mk_xt

Reputation: 561

The test is fine, in vue2 you have to add a root to the template. Component template should contain exactly one root element.

<div>
    <p>Count: {{ count }}</p>
    <button @click="handleClick">Increment</button>
</div>

Upvotes: 1

Related Questions