Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ export default tseslint.config(
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' },
{
argsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
varsIgnorePattern: '^_',
ignoreRestSiblings: true,
},
],
'@typescript-eslint/consistent-type-imports': ['warn', { prefer: 'type-imports' }],
// Downgrade new eslint-config-next v16 React Compiler rules to warnings
Expand Down
204 changes: 204 additions & 0 deletions src/ai/flows/workout-generator-flow.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { z } from 'zod';

const mockGenerate = vi.fn();
const mockGenerateStream = vi.fn();
const mockDefineFlow = vi.fn((_config: unknown, handler: unknown) => handler);
const mockSetAttribute = vi.fn();
const mockSpan = { setAttribute: mockSetAttribute };

vi.mock('@/ai/genkit', () => ({
ai: {
defineFlow: (...args: [unknown, unknown]) => mockDefineFlow(...args),
generate: (...args: [unknown]) => mockGenerate(...args),
generateStream: (...args: [unknown]) => mockGenerateStream(...args),
},
}));

vi.mock('@genkit-ai/google-genai', () => ({
googleAI: { model: vi.fn(() => 'gemini-2.5-flash') },
}));

vi.mock('@sentry/nextjs', () => ({
startSpan: vi.fn(async (_config: unknown, fn: (span: typeof mockSpan) => Promise<unknown>) =>
fn(mockSpan)
),
}));

vi.mock('@/lib/constants', () => ({
EXERCICIOS_POR_GRUPO: [
{
grupo: 'Peito',
exercicios: [{ nomeExercicio: 'Supino Reto' }],
},
],
}));

vi.mock('@/ai/schemas', () => {
const WorkoutGeneratorInputSchema = z.object({
objetivo: z.enum(['Hipertrofia', 'Perda de Peso', 'Força']),
nivelExperiencia: z.enum(['Iniciante', 'Intermediário', 'Avançado']),
diasPorSemana: z.number().min(1).max(7),
observacoesAdicionais: z.string().optional(),
});

const WorkoutGeneratorAIOutputSchema = z.object({
planName: z.string(),
workouts: z.array(
z.object({
nome: z.string(),
objetivo: z.string(),
diaSugerido: z.number(),
exercicios: z.array(
z.object({
nomeExercicio: z.string(),
grupoMuscular: z.string(),
series: z.number(),
repeticoes: z.string(),
observacoes: z.string(),
})
),
})
),
});

return {
WorkoutGeneratorInputSchema,
WorkoutGeneratorAIOutputSchema,
WorkoutGeneratorInput: undefined,
WorkoutGeneratorAIOutput: undefined,
};
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const validInput = {
objetivo: 'Hipertrofia' as const,
nivelExperiencia: 'Intermediário' as const,
diasPorSemana: 4,
};

describe('streamWorkoutPlan', () => {
beforeEach(() => {
vi.clearAllMocks();
});

it('streams workout plan successfully', async () => {
const chunkOutput = {
planName: 'Plano Teste',
workouts: [],
};
mockGenerateStream.mockReturnValue({
stream: (async function* () {
yield { output: chunkOutput };
})(),
response: Promise.resolve({
output: {
planName: 'Plano Teste',
workouts: [
{
nome: 'Treino A',
objetivo: 'Hipertrofia',
diaSugerido: 1,
exercicios: [
{
nomeExercicio: 'Supino Reto',
grupoMuscular: 'Peito',
series: 3,
repeticoes: '10-12',
observacoes: '',
},
],
},
],
},
usage: { inputTokens: 100, outputTokens: 200 },
}),
});

const { streamWorkoutPlan } = await import('@/ai/flows/workout-generator-flow');
const sendChunk = vi.fn();

const result = await (
streamWorkoutPlan as unknown as (
input: typeof validInput,
ctx: { sendChunk: (chunk: unknown) => void }
) => Promise<unknown>
)(validInput, { sendChunk });

expect(result).toBeDefined();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The streamWorkoutPlan success test has weak assertions that don't verify the actual return value structure or the specific chunk content sent via sendChunk. Unlike the generateWorkoutPlan test which validates result.planName, this test only checks toBeDefined() and toHaveBeenCalled(), reducing its regression-detection value.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/ai/flows/workout-generator-flow.test.ts, line 125:

<comment>The `streamWorkoutPlan` success test has weak assertions that don't verify the actual return value structure or the specific chunk content sent via `sendChunk`. Unlike the `generateWorkoutPlan` test which validates `result.planName`, this test only checks `toBeDefined()` and `toHaveBeenCalled()`, reducing its regression-detection value.</comment>

<file context>
@@ -0,0 +1,200 @@
+      ctx: { sendChunk: (chunk: unknown) => void }
+    ) => Promise<unknown>)(validInput, { sendChunk });
+
+    expect(result).toBeDefined();
+    expect(sendChunk).toHaveBeenCalled();
+  });
</file context>

expect(sendChunk).toHaveBeenCalled();
});

it('throws when AI returns no output', async () => {
mockGenerateStream.mockReturnValue({
stream: (async function* () {
yield {};
})(),
response: Promise.resolve({
output: null,
usage: { inputTokens: 0, outputTokens: 0 },
}),
});

const { streamWorkoutPlan } = await import('@/ai/flows/workout-generator-flow');
const sendChunk = vi.fn();

await expect(
(
streamWorkoutPlan as unknown as (
input: typeof validInput,
ctx: { sendChunk: (chunk: unknown) => void }
) => Promise<unknown>
)(validInput, { sendChunk })
).rejects.toThrow('A IA não retornou um plano de treino válido.');
});
});

describe('generateWorkoutPlan', () => {
beforeEach(() => {
vi.clearAllMocks();
});

it('generates workout plan successfully', async () => {
mockGenerate.mockResolvedValue({
output: {
planName: 'Plano Força',
workouts: [
{
nome: 'Treino A',
objetivo: 'Força',
diaSugerido: 2,
exercicios: [
{
nomeExercicio: 'Supino Reto',
grupoMuscular: 'Peito',
series: 5,
repeticoes: '5-6',
observacoes: '',
},
],
},
],
},
usage: { inputTokens: 50, outputTokens: 150 },
});

const { generateWorkoutPlan } = await import('@/ai/flows/workout-generator-flow');
const result = await generateWorkoutPlan(validInput);

expect(result).toBeDefined();
expect(result.planName).toBe('Plano Força');
expect(mockGenerate).toHaveBeenCalled();
});

it('throws when output is null', async () => {
mockGenerate.mockResolvedValue({
output: null,
usage: { inputTokens: 0, outputTokens: 0 },
});

const { generateWorkoutPlan } = await import('@/ai/flows/workout-generator-flow');
await expect(generateWorkoutPlan(validInput)).rejects.toThrow(
'A IA não retornou um plano de treino válido.'
);
});
});
50 changes: 50 additions & 0 deletions src/ai/genkit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';

const mockGenkit = vi.fn(() => ({ name: 'mocked-ai' }));

vi.mock('genkit', () => ({
genkit: mockGenkit,
}));

vi.mock('@genkit-ai/google-genai', () => ({
googleAI: vi.fn(() => 'google-ai-plugin'),
}));

describe('genkit initialization', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.resetModules();
});

it('initializes genkit with googleAI plugin', async () => {
const { ai } = await import('./genkit');
expect(mockGenkit).toHaveBeenCalledTimes(1);
expect(mockGenkit).toHaveBeenCalledWith(
expect.objectContaining({
plugins: expect.arrayContaining(['google-ai-plugin']),
})
);
expect(ai).toEqual({ name: 'mocked-ai' });
});

it('passes GOOGLE_GENAI_API_KEY to googleAI plugin', async () => {
process.env.GOOGLE_GENAI_API_KEY = 'test-key';
const { googleAI } = await import('@genkit-ai/google-genai');
await import('./genkit');

expect(googleAI).toHaveBeenCalledWith(expect.objectContaining({ apiKey: 'test-key' }));

delete process.env.GOOGLE_GENAI_API_KEY;
});

it('falls back to GEMINI_API_KEY when GOOGLE_GENAI_API_KEY is not set', async () => {
delete process.env.GOOGLE_GENAI_API_KEY;
process.env.GEMINI_API_KEY = 'fallback-key';
const { googleAI } = await import('@genkit-ai/google-genai');
await import('./genkit');

expect(googleAI).toHaveBeenCalledWith(expect.objectContaining({ apiKey: 'fallback-key' }));

delete process.env.GEMINI_API_KEY;
});
});
Loading
Loading