Jest · fixture · DENATRAN
Gerador de CNH em Jest
Fixture pra CNH válida em testes Jest. Session fixture, globalSetup, mock de DETRAN. Ideal pra app de motorista (Uber, 99, iFood entregadores). SDK fakeforge-br.
npm install --save-dev fakeforge-br
// tests/fixtures/cnh.ts
import { FakeForge } from "fakeforge-br"
export const ff = new FakeForge()Fixture com cache
// tests/fixtures/cnh-fixture.ts
import { FakeForge } from "fakeforge-br"
const ff = new FakeForge()
let cache: string[] | null = null
export async function getCNHs(qty = 20): Promise<string[]> {
if (!cache || cache.length < qty) {
cache = await ff.cnh(Math.max(qty, 100))
}
return cache.slice(0, qty)
}
export async function getMotoristaCompleto() {
const [[customer], [cnh]] = await Promise.all([
ff.preset("customer", 1),
ff.cnh(1),
])
return { ...customer, cnh }
}Teste E2E — cadastro motorista
// tests/motorista-signup.test.ts
import request from "supertest"
import app from "../src/app"
import { getMotoristaCompleto } from "./fixtures/cnh-fixture"
describe("POST /motoristas", () => {
test("cadastra motorista com CNH válida", async () => {
const dados = await getMotoristaCompleto()
const res = await request(app).post("/motoristas").send({
cpf: dados.cpf,
nome: dados.nome,
cnh: dados.cnh,
categoria: "B",
})
expect(res.status).toBe(201)
expect(res.body.aprovado).toBe(true)
})
test("rejeita CNH inválida", async () => {
const res = await request(app).post("/motoristas").send({
cpf: "123.456.789-09",
nome: "Test",
cnh: "11111111111", // Sequência inválida
categoria: "B",
})
expect(res.status).toBe(400)
})
})Mock de DETRAN
// tests/detran-check.test.ts
import { getCNHs } from "./fixtures/cnh-fixture"
jest.mock("../src/detran.client", () => ({
DetranClient: jest.fn().mockImplementation(() => ({
consultarCnh: jest.fn().mockResolvedValue({
valida: true,
pontos: 0,
restricoes: [],
vencimento: "2028-06-15",
}),
})),
}))
test("verifica CNH no DETRAN antes de aprovar motorista", async () => {
const { MotoristaService } = await import("../src/motorista.service")
const [cnh] = await getCNHs(1)
const service = new MotoristaService()
const result = await service.aprovarCadastro(cnh)
expect(result.aprovado).toBe(true)
expect(result.pontos).toBe(0)
})