DEV Community

Cover image for Como configurar teste unitário no Next.js14 com Jest.
Rafael Teles Vital
Rafael Teles Vital

Posted on

Como configurar teste unitário no Next.js14 com Jest.

Olá pessoal!

Testes unitários são uma prática essencial no desenvolvimento de software, visando garantir que partes específicas do código (unidades) funcionem conforme o esperado. Jest é uma ferramenta popular para realizar testes em JavaScript e TypeScript, e neste contexto, ele é frequentemente utilizado com aplicações construídas em React, Node.js e outros frameworks.

Instalando as dependências:

Para configurar o Jest vamos instalar pacotes jest, @testing-library/react e @testing-library/jest-dom:

yarn add -D jest @testing-library/react @testing-library/jest-dom
Enter fullscreen mode Exit fullscreen mode

Configurando o teste no projeto

É necessário criar um arquivo de configuração para que o Jest entenda como realizar os testes.

Crie um arquivo jest.config.js na raiz do seu projeto:

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)
Enter fullscreen mode Exit fullscreen mode

Agora, basta adicionar um script para executar os testes no package.json:

{
"scripts": {
"test": "jest --watch"
},
}

Pronto agora podemos criar nosso primeiro teste.

dentro do seu projeto criar um arquivo, por exemplo "exemplo.test.tsx" ou "exemplo.test.jsx"

it('Somando números', () => {
    expect(1 + 1).toBe(2)
  })
Enter fullscreen mode Exit fullscreen mode

Image description

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay