2

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

  • don't send any custom data to the mount method, or
  • force a re-render, using wrapper.vm.$forceUpdate() after triggering the event.

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

2 Answers 2

2
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')
})
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.