Jest · fixture · alfanumérico 2026
Gerador de CNPJ em Jest
Fixture pra CNPJ válido em testes Jest — cobre numérico e alfanumérico 2026 (IN RFB 2.229). Session fixture pra economizar quota, globalSetup pra batch, mock de serviço de validação. Tudo com SDK fakeforge-br.
TL;DR
npm install --save-dev fakeforge-br
// tests/fixtures/cnpj.ts
import { FakeForge } from "fakeforge-br"
export const ff = new FakeForge()Fixture reutilizável
// tests/fixtures/cnpj-fixture.ts
import { FakeForge } from "fakeforge-br"
const ff = new FakeForge()
let cache: { numeric: string[]; alfa: string[] } | null = null
async function ensureCache() {
if (!cache) {
const [numeric, alfa] = await Promise.all([ff.cnpj(100), ff.cnpjAlfa(50)])
cache = { numeric, alfa }
}
return cache
}
export async function getCNPJs(qty = 20): Promise<string[]> {
const c = await ensureCache()
return c.numeric.slice(0, qty)
}
export async function getCNPJsAlfa(qty = 10): Promise<string[]> {
const c = await ensureCache()
return c.alfa.slice(0, qty)
}Teste E2E — signup B2B com CNPJ
// tests/b2b-signup.test.ts
import request from "supertest"
import app from "../src/app"
import { getCNPJs, getCNPJsAlfa } from "./fixtures/cnpj-fixture"
describe("POST /b2b/signup", () => {
let cnpjsNumeric: string[]
let cnpjsAlfa: string[]
beforeAll(async () => {
cnpjsNumeric = await getCNPJs(10)
cnpjsAlfa = await getCNPJsAlfa(10)
})
test.each(0..10)("aceita CNPJ numérico #%i", async (i) => {
const res = await request(app).post("/b2b/signup").send({
cnpj: cnpjsNumeric[i],
razaoSocial: `Empresa ${i}`,
})
expect(res.status).toBe(201)
})
test.each(0..10)("aceita CNPJ alfanumérico 2026 #%i", async (i) => {
const res = await request(app).post("/b2b/signup").send({
cnpj: cnpjsAlfa[i],
razaoSocial: `Empresa Alfa ${i}`,
})
expect(res.status).toBe(201) // IN RFB 2.229
})
test("rejeita CNPJ inválido", async () => {
const res = await request(app).post("/b2b/signup").send({
cnpj: "11.111.111/1111-11",
razaoSocial: "Test",
})
expect(res.status).toBe(400)
})
})globalSetup pra volume alto
// jest.config.js
export default {
globalSetup: "./tests/global-setup.ts",
}
// tests/global-setup.ts
import { FakeForge } from "fakeforge-br"
import fs from "fs"
export default async function () {
const ff = new FakeForge()
const [cnpjs, cnpjsAlfa] = await Promise.all([
ff.cnpj(1000),
ff.cnpjAlfa(300),
])
fs.writeFileSync(".test-fixtures.json", JSON.stringify({ cnpjs, cnpjsAlfa }))
console.log(`Fixtures: ${cnpjs.length} num + ${cnpjsAlfa.length} alfa`)
}