DEV Community

Cover image for Vue 3 e Testes Unitários
Helton Carlos Brito Silva
Helton Carlos Brito Silva

Posted on

2

Vue 3 e Testes Unitários

Na busca pela construção de aplicativos super confiáveis, as empresas estão dando um show ao incentivar seus desenvolvedores front-end a arrasarem nos testes unitários! É a hora de brilhar, galera! 💻✨

Vamos agitar as coisas neste exemplo usando o framework front-end Vue.js 3, junto com a poderosa dupla Vitest e Vue Test Utils! 🚀 Preparados para a mágica acontecer?

1º Etapa

Entre no seu projeto e instale o vitest em seu projeto.

npm install -D vitest
Enter fullscreen mode Exit fullscreen mode

Vá ate o arquivo package.json e adicione:

{
  "scripts": {
    "test": "vitest"
  }
}
Enter fullscreen mode Exit fullscreen mode

Adicione também no arquivo vite.config.js

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  test: {
    globals: true,
    environment: 'jsdom',
  },
})

Enter fullscreen mode Exit fullscreen mode

2º Etapa

Hora de instalar Vue Test Utils, a biblioteca oficial de utilitários de teste para Vue.js!

npm install @vue/test-utils --save-dev
Enter fullscreen mode Exit fullscreen mode

Ao finalizar a instalação, use este comando no terminal:

npm install jsdom
Enter fullscreen mode Exit fullscreen mode

3º Etapa

É hora de mergulhar de cabeça no código! Vamos agitar as linhas e criar um componente para testar nossa aplicação como verdadeiros mestres da programação! 💻✨ Nesse exemplo incrível, estou prestes a mandar ver dentro do nosso querido componente App.vue, só para deixar todo mundo afiado nessa aula prática. Preparados para a jornada de aprendizado? 🚀

<script setup>
import { ref } from 'vue';

const count = ref(0)
</script>

<template>
  <div>
    <p data-test="text-value">
      value: {{ count }}
    </p>

    <button
      data-test="btn"
      type="button" 
      @click="count++"
    >
      increment
    </button>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

E depois crie esse arquivo, App.test.js adicione esse teste:

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

describe("App component", () => {
  test("Render App", () => {
    const component = mount(App);

    expect(component).toBeDefined();
  });

  test("Search by text", () => {
    const wrapper = mount(App);

    expect(wrapper.text()).toContain("value: 0");
  })

  test("triggers a click", () => {
    const wrapper = mount(App);

    const btn = wrapper.findAll('[data-test="btn"]');

    expect(btn).toHaveLength(1);
  })
});

Enter fullscreen mode Exit fullscreen mode

Vá ate o terminal e digite:

yarn test
Enter fullscreen mode Exit fullscreen mode

Resultado final:

Image description

como podemos ver todos os testes estão aprovados!

Quero agradecer a todos que chegaram ate aqui!

linkedin:
https://www.linkedin.com/in/helton-brito-856ba516b/

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (2)

Collapse
 
raulferreirasilva profile image
Raul Ferreira

Eu estou começando agora na area de teste e eu me senti meio perdido, teria como me explicar o que cada teste está fazendo? como ele viu que o count aumentou corretamente um? teria como fornecer um exemplo de uma requisição de uma api, fiquei curioso para saber como seria feito. Obrigado por compartilhar seu conhecimento 🦤.

Collapse
 
heltonbrito profile image
Helton Carlos Brito Silva

Olá Raul, espero que esteja tudo bem!

O primeiro teste assegura que o componente "App" pode ser renderizado corretamente.
No segundo teste, o componente "App" é renderizado e, em seguida, verifica-se se o texto contido nele (wrapper.text()) inclui a sequência inicial "value: 0".
No terceiro teste, estamos garantindo que o botão está funcionando, aumentando o valor de zero para um.

Já no exemplo da API, tem a lib jest supertest. Ela ajuda testar os endpoints das aplicações.

Em outros momentos criarei mais conteúdo sobre esse assunto, valeu!

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay