Skip to content

Ejemplos

Ejemplo Básico

vue
<template>
  <div>
    <p>Times clicked: {{ count }}</p>
    <button @click="increment">increment</button>
  </div>
</template>

<script>
  export default {
    data: () => ({
      count: 0,
    }),

    methods: {
      increment() {
        this.count++
      },
    },
  }
</script>
js
import {render, fireEvent} from '@testing-library/vue'
import Component from '@/Component.vue'

test('increments value on click', async () => {
  // The render method returns a collection of utilities to query your component.
  const {getByText} = render(Component)

  // getByText returns the first matching node for the provided text, and
  // throws an error if no elements match or if more than one match is found.
  getByText('Times clicked: 0')

  const button = getByText('increment')

  // Dispatch a native click event to our button element.
  await fireEvent.click(button)
  await fireEvent.click(button)

  getByText('Times clicked: 2')
})

Ejemplo usando v-model:

vue
<template>
  <div>
    <p>Hi, my name is {{ user }}</p>

    <label for="username">Username:</label>
    <input v-model="user" id="username" name="username" />
  </div>
</template>

<script>
  export default {
    data: () => ({
      user: 'Alice',
    }),
  }
</script>
js
import {render, fireEvent} from '@testing-library/vue'
import Component from '@/Component.vue'

test('properly handles v-model', async () => {
  const {getByLabelText, getByText} = render(Component)

  // Asserts initial state.
  getByText('Hi, my name is Alice')

  // Get the input DOM node by querying the associated label.
  const usernameInput = getByLabelText(/username/i)

  // Updates the <input> value and triggers an `input` event.
  // fireEvent.input() would make the test fail.
  await fireEvent.update(usernameInput, 'Bob')

  getByText('Hi, my name is Bob')
})

Más ejemplos

Encontrará ejemplos de pruebas con diferentes bibliotecas en el directorio de pruebas.

Algunos incluidos son: