Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { env } from 'cloudflare:test'
3
4import { getDb } from '../db/index.ts'
5import { createAuth } from './auth.ts'
6
7const TEST_SECRET = 'vitest-only-better-auth-secret'
8
9describe('better auth on D1 (real binding, migrated schema)', () => {
10 it('signs up a user and retrieves the session via bearer token', async () => {
11 const auth = createAuth(getDb(env), { secret: TEST_SECRET })
12
13 const signUp = await auth.api.signUpEmail({
14 body: {
15 name: 'Worker Tester',
16 email: 'worker-tester@example.com',
17 password: 'correct-horse-battery',
18 },
19 })
20 expect(signUp.user.email).toBe('worker-tester@example.com')
21 expect(signUp.token).toBeTruthy()
22
23 // The bearer plugin accepts the session token as an Authorization header.
24 const session = await auth.api.getSession({
25 headers: new Headers({ authorization: `Bearer ${signUp.token}` }),
26 })
27 expect(session?.user.email).toBe('worker-tester@example.com')
28 })
29
30 it('persists the user row in D1', async () => {
31 const auth = createAuth(getDb(env), { secret: TEST_SECRET })
32 await auth.api.signUpEmail({
33 body: {
34 name: 'Row Tester',
35 email: 'row-tester@example.com',
36 password: 'correct-horse-battery',
37 },
38 })
39
40 const row = await env.DB.prepare('SELECT email FROM user WHERE email = ?')
41 .bind('row-tester@example.com')
42 .first<{ email: string }>()
43 expect(row?.email).toBe('row-tester@example.com')
44 })
45})