Expert Class - Como Fazer Testes Unitário (Passo a Passo)

Expert Class - Como Fazer Testes Unitário (Passo a Passo)

  • O que é? São formas de testar seu código e assim deixá-lo com mais qualidade, tornando mais fácil de dar manutenção.
  • O que usamos para fazer? testing-library e jest, mas temos outras libs no mercado
  • Por onde começo?
    • Instale o testing-library e as dependências
npm install --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
  • Configure o Jest no seu projeto
// jest.config.js
const nextJest = require('next/jest')

const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: './',
})

// Add any custom config to be passed to Jest
const customJestConfig = {
  // Add more setup options before each test is run
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
}

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig)
  • Crie o script no package.json
"scripts": {
  "dev": "next dev",
  "build": "next build",
  "start": "next start",
  "test": "jest --watch"
}
  • Para criar seu primeiro teste unitário, crie um arquivo de teste para um component ou page
  • Suite Test → describe
  • Anatomia do teste:
    • Imports
import { render, screen } from '@testing-library/react'
import '@testing-library/jest-dom'
  • Renderização
render()
  • Localizar objeto de teste
screen.getXXX(XXX)
  • Simular eventos/interações
fireEvent.XXXX
  • Expectativa
expect(XXXXXX).toBeXXXXX
  • Alguns cenários de testes
    • Renderizou
    • Renderizou com um estilo (class)
    • Renderizou e interagiu com o usuário
  • Cobertura de teste
npm run test -- --coverage
  • Bônus
    • Truque com coverage (pagina escondida)

Assista o vídeo para entender como usar esse passo a passo: Youtube