-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.component.test.ts
More file actions
273 lines (230 loc) · 11.2 KB
/
Copy pathgenerator.component.test.ts
File metadata and controls
273 lines (230 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import '@angular/compiler';
import { Injector, runInInjectionContext } from '@angular/core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { GeneratorComponent } from './generator.component';
import { AuthService } from '../../services/auth.service';
import { PersistenceService } from '../../services/persistence.service';
import { GeminiService } from '../../services/gemini.service';
import { RecipeStateService } from '../../services/recipe-state.service';
import { ToastService } from '../../services/toast.service';
import { ModalService } from '../../services/modal.service';
// KAN-126 (#3209): GeneratorComponent carried ~13 methods byte-identical to
// RecipeDetailComponent but had no test file of its own, so the extraction
// into the shared base had no regression net on this side. These pin the
// shared behaviour *through the generator's surface* — above all the one
// branch where the two components legitimately differ (see the first test).
describe('GeneratorComponent shared recipe behaviour', () => {
let toastShow: ReturnType<typeof vi.fn>;
let openAuth: ReturnType<typeof vi.fn>;
beforeEach(() => {
toastShow = vi.fn();
openAuth = vi.fn();
});
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
const createComponent = (opts: { isGuest?: boolean } = {}) => {
const recipeState = runInInjectionContext(
Injector.create({ providers: [] }),
() => new RecipeStateService()
);
const persistenceSaveRecipe = vi.fn().mockResolvedValue({ ok: true });
const authUser = { isGuest: opts.isGuest ?? true, savedRecipes: [] as unknown[] };
const injector = Injector.create({
providers: [
{
provide: AuthService,
useValue: {
currentUser: () => authUser,
saveRecipe: vi.fn(),
updateRecipeField: vi.fn(),
ensureGuestSession: vi.fn(),
},
},
{
provide: PersistenceService,
useValue: {
saveRecipe: persistenceSaveRecipe,
saveRecipeDetailed: persistenceSaveRecipe,
// KAN-255 post-image reconcile; null = row unreadable, the
// branch that leaves the optimistic local write standing.
refreshRecipeFromApi: vi.fn().mockResolvedValue(null),
publishStateSync: () => 'synced',
},
},
{ provide: GeminiService, useValue: {} },
{ provide: RecipeStateService, useValue: recipeState },
{ provide: ToastService, useValue: { show: toastShow } },
{ provide: ModalService, useValue: { openAuth, openAddToCookbook: vi.fn() } },
],
});
const component = runInInjectionContext(injector, () => new GeneratorComponent());
return { component, persistenceSaveRecipe, authUser, recipeState, injector };
};
const draftRecipe = () =>
({
id: 'gen-1',
name: 'Vegan Cornbread',
ingredients: { wet: [], dry: [], other: [] },
instructions: [],
}) as never;
// THE divergence from RecipeDetailComponent: the generator prompts a guest to
// sign in, where recipe-detail returns silently (it renders a separate
// "Sign in to publish" button instead). An extraction that collapses both
// onto one implementation would silently drop this.
it('opens the auth modal when a guest tries to publish, and saves nothing', async () => {
const { component, persistenceSaveRecipe } = createComponent({ isGuest: true });
await component.togglePublic(draftRecipe());
expect(openAuth).toHaveBeenCalledOnce();
expect(persistenceSaveRecipe).not.toHaveBeenCalled();
});
it('publishes immutably for a signed-in user and adopts the server-minted slug', async () => {
const { component, persistenceSaveRecipe, authUser } = createComponent({ isGuest: false });
const recipe = draftRecipe() as unknown as { id: string; is_public?: boolean; slug?: string };
component.recipe.set(recipe as never);
persistenceSaveRecipe.mockImplementation(async (saved: { slug?: string }) => {
// The client must not predict a slug — the server mints it (#3262).
expect(saved.slug).toBeUndefined();
authUser.savedRecipes = [{ ...recipe, is_public: true, slug: 'vegan-cornbread-2' }];
return { ok: true };
});
await component.togglePublic(recipe as never);
expect(recipe.is_public).toBeFalsy(); // passed object never mutated
const viewed = component.recipe() as { is_public?: boolean; slug?: string } | null;
expect(viewed?.is_public).toBe(true);
expect(viewed?.slug).toBe('vegan-cornbread-2');
});
it('blocks publishing a manually entered recipe with a toast', async () => {
const { component, persistenceSaveRecipe } = createComponent({ isGuest: false });
await component.togglePublic({ ...(draftRecipe() as object), origin: 'manual' } as never);
expect(toastShow).toHaveBeenCalledWith(expect.stringMatching(/manually entered/i));
expect(persistenceSaveRecipe).not.toHaveBeenCalled();
});
it('ignores toggle attempts on a canonical recipe', async () => {
const { component, persistenceSaveRecipe } = createComponent({ isGuest: false });
await component.togglePublic({
...(draftRecipe() as object),
is_canonical: true,
is_public: true,
slug: 'vegan-cornbread',
} as never);
expect(persistenceSaveRecipe).not.toHaveBeenCalled();
});
it('blocks a title that derives an empty slug and says why', async () => {
const { component, persistenceSaveRecipe } = createComponent({ isGuest: false });
await component.togglePublic({ ...(draftRecipe() as object), name: '🌮🌮🌮' } as never);
expect(toastShow).toHaveBeenCalledWith(expect.stringMatching(/can't be published/i));
expect(persistenceSaveRecipe).not.toHaveBeenCalled();
});
// RCP-74: saved copies cannot be published. The guard refuses with the D1
// redirect toast — "already live at [here]" linking the source's public
// page. confirm is stubbed to ACCEPT so a reintroduced KAN-137-style
// confirm flow would publish and fail this test (poison pill).
it('blocks publishing a saved copy with the already-live link toast (RCP-74)', async () => {
const confirmMock = vi.fn().mockReturnValue(true);
vi.stubGlobal('confirm', confirmMock);
const { component, persistenceSaveRecipe } = createComponent({ isGuest: false });
await component.togglePublic({
...(draftRecipe() as object),
sourceSlug: 'vegan-cornbread',
} as never);
expect(confirmMock).not.toHaveBeenCalled();
expect(toastShow).toHaveBeenCalledWith(
expect.stringMatching(/already live/i),
null,
expect.any(Number),
{ url: '/r/vegan-cornbread', label: 'here' }
);
expect(persistenceSaveRecipe).not.toHaveBeenCalled();
});
it('reverts the viewed signal and toasts when the publish fails to sync', async () => {
const { component, persistenceSaveRecipe } = createComponent({ isGuest: false });
persistenceSaveRecipe.mockResolvedValue(false);
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
const recipe = draftRecipe() as unknown as { is_public?: boolean };
component.recipe.set(recipe as never);
await component.togglePublic(recipe as never);
const viewed = component.recipe() as { is_public?: boolean } | null;
expect(viewed?.is_public).toBeFalsy();
expect(toastShow).toHaveBeenCalledWith(expect.stringMatching(/publishing failed to sync/i));
expect(consoleError).toHaveBeenCalled();
});
// KAN-140: generated notes render live on /r/<slug>, so the editor only ever
// touches the private personalNotes field.
it('notes editor opens with personalNotes and never rewrites the generated notes', async () => {
const { component } = createComponent({ isGuest: false });
component.recipe.set({
...(draftRecipe() as object),
notes: 'generated public notes',
personalNotes: 'my private tweaks',
} as never);
component.startEditNotes();
expect(component.editedNotes()).toBe('my private tweaks');
component.editedNotes.set('do not tell the internet');
await component.saveNotes();
const saved = component.recipe() as { notes?: string; personalNotes?: string } | null;
expect(saved?.notes).toBe('generated public notes');
expect(saved?.personalNotes).toBe('do not tell the internet');
});
it('scales ingredient amounts and servings by the portion multiplier', () => {
const { component } = createComponent({ isGuest: false });
component.recipe.set({
...(draftRecipe() as object),
servings: 4,
ingredients: { dry: [{ name: 'flour', amount: 2, unit: 'cup' }] },
} as never);
component.updatePortions(2);
expect(component.scaledServings()).toBe(8);
expect(component.scaledIngredients()?.dry?.[0].amount).toBe(4);
});
it('formats common fractional amounts', () => {
const { component } = createComponent();
expect(component.formatAmount(0.25)).toBe('1/4');
expect(component.formatAmount(0.5)).toBe('1/2');
expect(component.formatAmount(2)).toBe('2');
expect(component.formatAmount([1, 2])).toBe('1 - 2');
});
// KAN-256: `clearRecipe()` fired inside onGenerate() — submit-time, not
// entry-time. The recipe lives on RecipeStateService (a root singleton) so
// it outlived the component, and navigating back to the generator re-showed
// the previous result under an empty prompt box. Route entry recreates the
// component, so constructing a second one IS the repro.
describe('route entry reset (KAN-256)', () => {
it('shows an empty form when the generator is entered again', () => {
const { component, recipeState, injector } = createComponent({ isGuest: false });
recipeState.viewRecipe(draftRecipe());
expect(component.recipe()).not.toBeNull();
const reEntered = runInInjectionContext(injector, () => new GeneratorComponent());
expect(reEntered.recipe()).toBeNull();
expect(reEntered.prompt()).toBe('');
expect(reEntered.error()).toBeNull();
expect(reEntered.isSaved()).toBe(false);
});
it('does not cancel an in-flight image generation for the previous recipe', async () => {
// The spinner and the KAN-255 reconcile are tracked by recipe id on the
// service, so leaving the generator must not discard them — recipe-detail
// still has to show the spinner for that recipe.
const { recipeState, injector } = createComponent({ isGuest: false });
let settle: (url: string) => void = () => {};
recipeState.trackImageGeneration(
'gen-1',
new Promise<string>((resolve) => {
settle = resolve;
})
);
recipeState.viewRecipe(draftRecipe());
expect(recipeState.isImageGenerating()).toBe(true);
runInInjectionContext(injector, () => new GeneratorComponent());
// Cleared here (nothing is being viewed)...
expect(recipeState.currentRecipe()).toBeNull();
// ...but still tracked, so the recipe's own page still spins.
recipeState.viewRecipe(draftRecipe());
expect(recipeState.isImageGenerating()).toBe(true);
settle('/api/recipes/gen-1/image');
await Promise.resolve();
await Promise.resolve();
expect(recipeState.isImageGenerating()).toBe(false);
});
});
});