Skip to content

Commit 894039b

Browse files
committed
🚨 Improve tests (#2446)
1 parent 41a2ecb commit 894039b

File tree

2 files changed

+50
-21
lines changed

2 files changed

+50
-21
lines changed

src/test/lib/utils/auth_forms.test.ts

Lines changed: 38 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { vi, expect, describe, beforeEach, afterEach, test } from 'vitest';
2+
import type { SuperValidated } from 'sveltekit-superforms';
23

34
// Mock external dependencies BEFORE importing the module under test
45
vi.mock('@sveltejs/kit', () => {
@@ -113,10 +114,10 @@ describe('auth_forms', () => {
113114
password: { type: 'string' },
114115
} as unknown,
115116
message: '',
116-
} as unknown as ReturnType<typeof superValidate>),
117+
} as unknown as SuperValidated<Record<string, string>, string>),
117118
);
118119

119-
vi.mocked(zod).mockImplementation(() => ({}) as ReturnType<typeof zod>);
120+
vi.mocked(zod).mockImplementation((schema: unknown) => schema as any);
120121
});
121122

122123
afterEach(() => {
@@ -197,14 +198,13 @@ describe('auth_forms', () => {
197198
const result = await createAuthFormWithFallback();
198199

199200
expect(result.form.id).toContain('error-fallback-form-');
200-
expect(crypto.randomUUID).toHaveBeenCalled();
201+
expect(globalThis.crypto.randomUUID).toHaveBeenCalled();
201202
});
202203

203204
test('expect to use fallback ID generation when crypto.randomUUID is unavailable', async () => {
204-
// Mock crypto.randomUUID to be undefined
205-
vi.stubGlobal('crypto', {
206-
randomUUID: undefined,
207-
});
205+
// Mock crypto.randomUUID to be undefined (preserve other properties)
206+
const prevCrypto = globalThis.crypto;
207+
vi.stubGlobal('crypto', { ...(prevCrypto ?? {}), randomUUID: undefined });
208208

209209
vi.mocked(superValidate).mockRejectedValueOnce(new Error('Primary strategy failed'));
210210

@@ -223,7 +223,12 @@ describe('auth_forms', () => {
223223
expect(result.form).toBeDefined();
224224
expect(result.form.data).toEqual({ username: '', password: '' });
225225
expect(result.form.id).toContain('error-fallback-form-');
226-
expect(mockConsoleWarn).toHaveBeenCalled();
226+
227+
if (import.meta.env.DEV) {
228+
expect(mockConsoleWarn).toHaveBeenCalled();
229+
} else {
230+
expect(mockConsoleWarn).not.toHaveBeenCalled();
231+
}
227232
});
228233
});
229234

@@ -258,7 +263,12 @@ describe('auth_forms', () => {
258263
expect(result).toBeDefined();
259264
// When validation fails, but another strategy succeeds, valid could be true
260265
expect(result.posted).toBe(true);
261-
expect(mockConsoleWarn).toHaveBeenCalled();
266+
267+
if (import.meta.env.DEV) {
268+
expect(mockConsoleWarn).toHaveBeenCalled();
269+
} else {
270+
expect(mockConsoleWarn).not.toHaveBeenCalled();
271+
}
262272
});
263273

264274
test('expect to handle complex form data', async () => {
@@ -289,13 +299,17 @@ describe('auth_forms', () => {
289299

290300
await createAuthFormWithFallback();
291301

292-
expect(mockConsoleWarn).toHaveBeenCalledWith(
293-
'Create authForm strategy: Failed to (Basic case) Use standard superValidate',
294-
);
295-
// Error objects are converted to string and include stack trace
296-
expect(mockConsoleWarn).toHaveBeenCalledWith(
297-
expect.stringContaining('Error: Test error message'),
298-
);
302+
if (import.meta.env.DEV) {
303+
expect(mockConsoleWarn).toHaveBeenCalledWith(
304+
'Create authForm strategy: Failed to (Basic case) Use standard superValidate',
305+
);
306+
// Error objects are converted to string and include stack trace
307+
expect(mockConsoleWarn).toHaveBeenCalledWith(
308+
expect.stringContaining('Error: Test error message'),
309+
);
310+
} else {
311+
expect(mockConsoleWarn).not.toHaveBeenCalled();
312+
}
299313
});
300314

301315
// Note: "expect to not log warnings in production mode" was removed
@@ -310,10 +324,14 @@ describe('auth_forms', () => {
310324

311325
await createAuthFormWithFallback();
312326

313-
expect(mockConsoleWarn).toHaveBeenCalledWith(
314-
'Create authForm strategy: Failed to (Basic case) Use standard superValidate',
315-
);
316-
expect(mockConsoleWarn).toHaveBeenCalledWith('String error');
327+
if (import.meta.env.DEV) {
328+
expect(mockConsoleWarn).toHaveBeenCalledWith(
329+
'Create authForm strategy: Failed to (Basic case) Use standard superValidate',
330+
);
331+
expect(mockConsoleWarn).toHaveBeenCalledWith('String error');
332+
} else {
333+
expect(mockConsoleWarn).not.toHaveBeenCalled();
334+
}
317335
});
318336
});
319337

src/test/lib/utils/authorship.test.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { expect, test, describe, vi } from 'vitest';
1+
import { expect, test, describe, vi, afterEach } from 'vitest';
22

33
// Mock modules
44
vi.mock('@sveltejs/kit', () => {
@@ -15,6 +15,10 @@ vi.mock('@sveltejs/kit', () => {
1515
return { redirect: vi.fn(redirectImpl) };
1616
});
1717

18+
afterEach(() => {
19+
vi.clearAllMocks();
20+
});
21+
1822
import {
1923
ensureSessionOrRedirect,
2024
getLoggedInUser,
@@ -48,6 +52,7 @@ describe('ensureSessionOrRedirect', () => {
4852
} as unknown as App.Locals;
4953

5054
await expect(ensureSessionOrRedirect(mockLocals)).resolves.toBeUndefined();
55+
expect(mockLocals.auth.validate).toHaveBeenCalledTimes(1);
5156
});
5257

5358
test('expect to redirect when user has no session', async () => {
@@ -59,6 +64,7 @@ describe('ensureSessionOrRedirect', () => {
5964

6065
await expect(ensureSessionOrRedirect(mockLocals)).rejects.toMatchObject({
6166
name: 'Redirect',
67+
status: expect.any(Number),
6268
location: '/login',
6369
});
6470
});
@@ -89,6 +95,7 @@ describe('getLoggedInUser', () => {
8995

9096
await expect(getLoggedInUser(mockLocals)).rejects.toMatchObject({
9197
name: 'Redirect',
98+
status: expect.any(Number),
9299
location: '/login',
93100
});
94101
});
@@ -103,6 +110,7 @@ describe('getLoggedInUser', () => {
103110

104111
await expect(getLoggedInUser(mockLocals)).rejects.toMatchObject({
105112
name: 'Redirect',
113+
status: expect.any(Number),
106114
location: '/login',
107115
});
108116
});
@@ -173,6 +181,8 @@ describe('Logged-in user id', () => {
173181
{ isPublished: false, userId: adminId, authorId: adminId },
174182
{ isPublished: false, userId: userId1, authorId: userId1 },
175183
{ isPublished: false, userId: userId2, authorId: userId2 },
184+
{ isPublished: false, userId: 'USER123', authorId: 'user123' },
185+
{ isPublished: false, userId: 'AuthorX', authorId: 'authorx' },
176186
];
177187
runTests('canRead', testCases, ({ isPublished, userId, authorId }: AuthorshipForRead) => {
178188
expect(canRead(isPublished, userId, authorId)).toBe(true);
@@ -293,6 +303,7 @@ describe('Logged-in user id', () => {
293303
{ userId: adminId, authorId: adminId },
294304
{ userId: userId1, authorId: userId1 },
295305
{ userId: userId2, authorId: userId2 },
306+
{ userId: 'UserX', authorId: 'userx' },
296307
];
297308
runTests('canDelete', testCases, ({ userId, authorId }: AuthorshipForDelete) => {
298309
expect(canDelete(userId, authorId)).toBe(true);

0 commit comments

Comments
 (0)