DEV Community

Cover image for Como testar watch do Vue.js usando Jest
Dedicio Coelho
Dedicio Coelho

Posted on

1

Como testar watch do Vue.js usando Jest

O Vue.js tem uma propriedade watch que serve para "observar" o valor de uma variável e ser executado sempre que esse valor for alterado.

Como essa propriedade serve para executar ações extras que não tenham alguma ligação a variável que dispara, existem alguns detalhes que devem ser seguidos para testar essa ação.

O componente exemplo para o teste é esse abaixo, tendo um data text que é usado no v-model do input

<template>
  <div>
    <input v-model="text">
    <p>Impactou: {{ otherText }}</p>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      text: '',
      otherText: '',
    };
  },
  watch: {
    text(value) {
      this.otherText = value;
    },
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

Para testar o watch, precisamos usar um código no estilo abaixo:

  it('testing watch', async () => {
    const text = 'example value';
    const wrapper = shallowMount(App);
    const input = wrapper.find('input');

    expect(wrapper.vm.otherText).toBe('');

    input.element.value = text;
    input.trigger('input');
    await wrapper.vm.$nextTick();

    expect(wrapper.vm.otherText).toBe(text);
  });
Enter fullscreen mode Exit fullscreen mode

Explicando o código:

Primeiro montamos o componente e pegamos o elemento input.

A ideia para testar o watch é sempre pegarmos o valor inicial da variável, executar a ação que ocorrerá no componente, aquela que altera a variável "assistida" pelo watch, e então verificar se houve algum efeito na variável que deveria ser afetada.

Verificando o valor antes:
expect(wrapper.vm.otherText).toBe('');

Executando a ação:
input.trigger('input');

Verificando o valor depois:
expect(wrapper.vm.otherText).toBe(text);

Como o ideal é testar um comportamento mais próximo do real, evite testar algo alterando o valor direto na instância do componente, como wrapper.vm.text = 'value'. Por isso aqui, inserimos um valor ao input e emitimos o evento input.

Detalhe

Caso o seu watch venha a verificar se um valor alterado volte ao valor padrão, será necessário executar a ação mais de uma vez, já que se você executar uma ação passando o valor igual ao valor anterior, o watch não é disparado.

Photo by Yassin Mohammadi on Unsplash

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay