DEV Community

Yan.ts
Yan.ts

Posted on

4 3

Testes E2E

Apesar de eu ser muito acostumado a fazer testes unitários até hoje não escrevi nenhum teste End to End. Então hoje finalmente decidi aprender como fazer testes E2E

Tudo que eu descrever aqui nesse post foi feito no seguinte repositório

Escrevendo testes E2E

Primeiro precisei declarar o app usando express, e também a conexão com o banco usando o sequelize

export const app: Express = express();

app.use(express.json());

export let sequelize: Sequelize;

async function setupDb() {
  sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: ':memory:',
    logging: false
  });

  sequelize.addModels([CustomerModel, ProductModel])
  await sequelize.sync()
}

setupDb();
Enter fullscreen mode Exit fullscreen mode

E então no meu arquivo de testes importei ambos junto com a função request do supertest
e então comecei declarando no beforeEach que o sequelize deve sempre recriar o schema antes de um novo teste e no afterAll fechei a conexão com o banco de dados

import {app, sequelize} from "../express"
import request from "supertest"

describe("E2E test for customer", () => {

  beforeEach(async () => {
    await sequelize.sync({force: true})
  })

  afterAll(async () => {
    await sequelize.close()
  })

  it("should create a customer", async () => {
    const response = await request(app)
      .post("/customer")
      .send({
        name: "John Doe",
        address: {
          street: "123 Main St",
          city: "Anytown",
          number: 123,
          zip: "12345"
        },
      });

    expect(response.status).toBe(201)
    expect(response.body.name).toBe("John Doe")
    expect(response.body.address.street).toBe("123 Main St")
  })

})
Enter fullscreen mode Exit fullscreen mode

O teste fica basicamente assim, acabou sendo muito mais fácil do que imaginei que seria, agora basta garantir que meu endpoint /customer do tipo POST vai retornar os dados no formato esperado

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

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

Okay