chore: sync main from Aceleradora25 - fix ordenar sequence e feat util pagination tests#73
Conversation
…into 64/feat-util-pagination-tests
…torno quando o filtro não for padrão
64/feat util pagination tests
70/fix bug ordenar sequence
|
@jauregao is attempting to deploy a commit to the Aceleradora Ágil's projects Team on Vercel. A member of the Team first needs to authorize it. |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
Pull request overview
Este PR sincroniza alterações da main do repositório upstream, com foco em corrigir a ordenação por sequence nos dados retornados pelo Stackby e em adicionar/ajustar testes de paginação e de serviços.
Changes:
- Ajusta
StackbyService.fetchStackbyDatapara normalizarfield.sequencee ordenar os itens retornados. - Adiciona testes para a util de paginação e para
ThemeService.getThemes. - Ajusta teste de
StackbyService(endpoint) e pequenas alterações de mocks/estilo em testes do login.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 9 comments.
Show a summary per file
| File | Description |
|---|---|
| src/utils/pagination.test.ts | Adiciona cobertura de testes para cálculo de skip/take e limites permitidos. |
| src/services/theme/ThemeService.ts | Ajusta criação de theme (sequence) e adiciona log de debug durante getThemes. |
| src/services/theme/ThemeService.test.ts | Cria teste para validar parâmetros de paginação passados ao Prisma e meta retornada. |
| src/services/StackbyService.ts | Normaliza sequence para número, ordena o retorno e força shape StackbyDataResponse. |
| src/services/StackbyService.test.ts | Atualiza endpoint usado no teste de fetchStackbyData. |
| src/controllers/login/LoginController.test.ts | Ajustes de formatação e alteração de roles em mocks. |
Comments suppressed due to low confidence (1)
src/services/StackbyService.test.ts:35
- Este teste agora mocka
response.json()como{ data: "ok" }, masfetchStackbyDatapassou a assumirdata.datacomo array para ordenar/mapear. Com o código atual, isso quebra ("ok".map is not a function) e a asserção final também não bate (o service retorna{ data: orderedData }). Ajuste o mock para retornar uma estrutura compatível ({ data: [{ field: { sequence: "1", ... }, ... }] }) e atualize a expectativa para refletir o shape retornado.
it("retorna dados em caso de sucesso", async () => {
const mockJson = jest.fn().mockResolvedValue({ data: "ok" });
(fetch as jest.Mock).mockResolvedValue({ json: mockJson, ok: true });
const result = await service.fetchStackbyData("Themes", null);
expect(fetch).toHaveBeenCalledWith(
expect.stringContaining("http://fakeurl/Themes"),
expect.objectContaining({
headers: expect.objectContaining({
"x-api-key": "fakekey",
}),
method: "GET",
}),
);
expect(result).toEqual({ data: "ok" });
});
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| take, | ||
| }); | ||
|
|
||
| themes.forEach(t => console.log(t.title, t.sequence)); |
There was a problem hiding this comment.
Remover este console.log/forEach (debug). Além de poluir logs em produção e impactar performance, pode vazar dados e interfere em ambientes serverless/observabilidade. Se precisar de logging, use o logger padrão do projeto com nível apropriado e behind feature flag.
| themes.forEach(t => console.log(t.title, t.sequence)); |
| }, | ||
| ); | ||
|
|
||
| return result as StackbyDataResponse; |
There was a problem hiding this comment.
cacheOrFetch pode retornar string quando o valor vem do Redis (redis.get), mas aqui o retorno é forçado para StackbyDataResponse via type assertion. Isso pode causar runtime errors em quem consome o resultado (ex.: tentar acessar result.data). Sugestão: fazer JSON.parse quando typeof result === "string" (ou, melhor, ajustar cacheOrFetch para sempre retornar T, parseando o cache).
| return result as StackbyDataResponse; | |
| const parsedResult: StackbyDataResponse = | |
| typeof result === "string" ? JSON.parse(result) : result; | |
| return parsedResult; |
| const orderedData = data.data | ||
| .map((t: any) => ({ | ||
| ...t, | ||
| field: { | ||
| ...t.field, | ||
| sequence: Number(t.field.sequence), | ||
| }, | ||
| })) | ||
| .sort((a: any, b: any) => a.field.sequence - b.field.sequence); |
There was a problem hiding this comment.
A conversão Number(t.field.sequence) pode resultar em NaN se sequence vier vazio/undefined; nesse caso o .sort fica instável e a ordenação pode sair incorreta. Para garantir ordenação determinística, normalize para um número válido (ex.: fallback 0) e/ou trate itens sem field.sequence.
| import { ThemeService } from "./ThemeService"; | ||
| import prisma from "../../../client"; | ||
|
|
||
| jest.mock("../../../client", () => ({ |
There was a problem hiding this comment.
Este teste está usando imports sem sufixo .js (e.g. "./ThemeService", "../../../client"), enquanto o resto do repo (Jest ESM + moduleNameMapper) padroniza imports com .js nos arquivos TS. Sem o sufixo, a resolução pode falhar em ESM. Sugestão: alinhar os imports para "./ThemeService.js" e "../../../client.js" (e manter o mesmo path no jest.mock).
| import { ThemeService } from "./ThemeService"; | |
| import prisma from "../../../client"; | |
| jest.mock("../../../client", () => ({ | |
| import { ThemeService } from "./ThemeService.js"; | |
| import prisma from "../../../client.js"; | |
| jest.mock("../../../client.js", () => ({ |
| __esModule: true, | ||
| default: { | ||
| theme: { | ||
| findMany: jest.fn(), | ||
| count: jest.fn(), | ||
| }, | ||
| }, | ||
| })); | ||
|
|
||
| describe("ThemeService - getThemes", () => { | ||
| let service: ThemeService; | ||
|
|
||
| beforeEach(() => { | ||
| service = new ThemeService(); | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| it("deve chamar o prisma com os valores de paginação corretos", async () => { | ||
| const mockThemes = [{ id: "1", title: "Tema Teste" }]; | ||
| (prisma.theme.findMany as jest.Mock).mockResolvedValue(mockThemes); | ||
| (prisma.theme.count as jest.Mock).mockResolvedValue(1); | ||
|
|
||
| const page = 1; | ||
| const limit = 10; | ||
|
|
||
| const result = await service.getThemes(undefined, page, limit); | ||
|
|
||
| expect(prisma.theme.findMany).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| skip: 0, | ||
| take: 10, | ||
| }) | ||
| ); | ||
|
|
||
| expect(result.meta.total).toBe(1); | ||
| expect(result.meta.totalPages).toBe(1); | ||
| expect(result.data).toEqual(mockThemes); | ||
| }); |
There was a problem hiding this comment.
O arquivo está formatado com espaços, mas o Biome do projeto está configurado para indentStyle: "tab" em src/**/*.ts. Isso tende a gerar ruído em diffs e falhas/ajustes automáticos de formatação. Rode o formatter (Biome) ou ajuste a indentação para tabs para manter consistência.
| __esModule: true, | |
| default: { | |
| theme: { | |
| findMany: jest.fn(), | |
| count: jest.fn(), | |
| }, | |
| }, | |
| })); | |
| describe("ThemeService - getThemes", () => { | |
| let service: ThemeService; | |
| beforeEach(() => { | |
| service = new ThemeService(); | |
| jest.clearAllMocks(); | |
| }); | |
| it("deve chamar o prisma com os valores de paginação corretos", async () => { | |
| const mockThemes = [{ id: "1", title: "Tema Teste" }]; | |
| (prisma.theme.findMany as jest.Mock).mockResolvedValue(mockThemes); | |
| (prisma.theme.count as jest.Mock).mockResolvedValue(1); | |
| const page = 1; | |
| const limit = 10; | |
| const result = await service.getThemes(undefined, page, limit); | |
| expect(prisma.theme.findMany).toHaveBeenCalledWith( | |
| expect.objectContaining({ | |
| skip: 0, | |
| take: 10, | |
| }) | |
| ); | |
| expect(result.meta.total).toBe(1); | |
| expect(result.meta.totalPages).toBe(1); | |
| expect(result.data).toEqual(mockThemes); | |
| }); | |
| __esModule: true, | |
| default: { | |
| theme: { | |
| findMany: jest.fn(), | |
| count: jest.fn(), | |
| }, | |
| }, | |
| })); | |
| describe("ThemeService - getThemes", () => { | |
| let service: ThemeService; | |
| beforeEach(() => { | |
| service = new ThemeService(); | |
| jest.clearAllMocks(); | |
| }); | |
| it("deve chamar o prisma com os valores de paginação corretos", async () => { | |
| const mockThemes = [{ id: "1", title: "Tema Teste" }]; | |
| (prisma.theme.findMany as jest.Mock).mockResolvedValue(mockThemes); | |
| (prisma.theme.count as jest.Mock).mockResolvedValue(1); | |
| const page = 1; | |
| const limit = 10; | |
| const result = await service.getThemes(undefined, page, limit); | |
| expect(prisma.theme.findMany).toHaveBeenCalledWith( | |
| expect.objectContaining({ | |
| skip: 0, | |
| take: 10, | |
| }) | |
| ); | |
| expect(result.meta.total).toBe(1); | |
| expect(result.meta.totalPages).toBe(1); | |
| expect(result.data).toEqual(mockThemes); | |
| }); |
| @@ -0,0 +1,68 @@ | |||
| process.env.STACKBY_BASE_URL = "http://fakeurl"; | |||
|
|
|||
| import { pagination } from "./pagination"; | |||
There was a problem hiding this comment.
Este teste está usando import sem sufixo .js (import { pagination } from "./pagination"), enquanto o repo usa padrão ESM com imports em .js nos arquivos TS. Para evitar problemas de resolução e manter consistência, prefira "./pagination.js".
| import { pagination } from "./pagination"; | |
| import { pagination } from "./pagination.js"; |
| provider: 'google', | ||
| role: Role.VIEWER, | ||
| provider: "google", | ||
| role: Role.ADMIN, |
There was a problem hiding this comment.
Nos mocks deste teste o usuário é retornado com role: Role.ADMIN, mas TokenService.registerUser() não define role e o schema Prisma tem default VIEWER. Mesmo que o controller não use o campo hoje, manter o mock alinhado ao comportamento real evita confusão e falsos positivos em futuras validações baseadas em role.
| role: Role.ADMIN, | |
| role: Role.VIEWER, |
| process.env.STACKBY_BASE_URL = "http://fakeurl"; | ||
|
|
There was a problem hiding this comment.
process.env.STACKBY_BASE_URL é setado aqui, mas esta suíte só testa pagination() e não depende de Stackby/env vars. Isso adiciona ruído e pode mascarar dependências reais de configuração em outros testes. Sugestão: remover essa linha ou manter apenas env vars estritamente necessárias para o teste.
| process.env.STACKBY_BASE_URL = "http://fakeurl"; |
| provider: 'github', | ||
| role: Role.VIEWER, | ||
| provider: "github", | ||
| role: Role.ADMIN, |
There was a problem hiding this comment.
Nos mocks deste teste o usuário criado é retornado com role: Role.ADMIN, mas TokenService.registerUser() não define role e o schema Prisma tem default VIEWER. Mesmo que o controller não use o campo hoje, manter o mock alinhado ao comportamento real evita confusão e falsos positivos em futuras validações baseadas em role.
| role: Role.ADMIN, | |
| role: Role.VIEWER, |
Este PR sincroniza as últimas alterações mergeadas na main do Aceleradora25/e-acelera-back para o repositório aceleradora-TW/e-acelera-back.
🆙 CHANGELOG
[#60] fix: bug ordenar sequence (ver PR original)
Corrigida ordenação dos dados retornados pela API do Stackby
Conversão do campo field.sequence para número antes da ordenação
Garantido retorno no formato StackbyDataResponse
[#57] feat: util pagination tests (ver PR original)
Criação de testes para ThemeService validando cálculo de skip, take e objeto meta
Correção do mock no StackbyService.test.ts (de "endpoint" para "Themes")
Implementação da utilitária centralizada de paginação em src/utils/pagination.util.ts
Testes passando: ThemeService.test.ts, StackbyService.test.ts, pagination.test.ts