Better-auth and e2e tests

Hello, So I've encountered a difficulty creating fake users for e2e testing in playwright. I dont know how to generate fake token to add to the cookies. I've inspected the valid cookie with an account logged in normally and it seems like its just a session token + "." + some string in the end , ex: 123abc.123abc, but I have no idea how to generate that string. I would guess that its based on the secret. Thats what I've tried:
export async function loginAsTestUser(
context: BrowserContext,
) {
const email = `test-user-${crypto.randomUUID()}@example.com`;
const { data, error } = await authClient.signUp.email({
email: email,
password: "password1234",
name: "test",
image: "https://example.com/image.png",
});
if (!data?.token) {
throw new Error("Failed to create test user");
}
await context.addCookies([
{
name: "better-auth.session_token",
value: data.token,
domain: "localhost",
path: "/",
httpOnly: true,
sameSite: "Lax",
expires: -1,
}
]);
}
export async function loginAsTestUser(
context: BrowserContext,
) {
const email = `test-user-${crypto.randomUUID()}@example.com`;
const { data, error } = await authClient.signUp.email({
email: email,
password: "password1234",
name: "test",
image: "https://example.com/image.png",
});
if (!data?.token) {
throw new Error("Failed to create test user");
}
await context.addCookies([
{
name: "better-auth.session_token",
value: data.token,
domain: "localhost",
path: "/",
httpOnly: true,
sameSite: "Lax",
expires: -1,
}
]);
}
I've also searched the docs for some examples or maybe methods to generate it, but no luck. Anyone knows what to do?
Solution:
instead of strong the token from the response, parse the setCookie header and use that instead. ```ts await authClient.signUp.email({}, { onSuccess: (ctx)=>{...
Jump to solution
4 Replies
Solution
bekacru
bekacru2w ago
instead of strong the token from the response, parse the setCookie header and use that instead.
await authClient.signUp.email({}, {
onSuccess: (ctx)=>{
const setCookieHeader = ctx.response.headers.get("set-cookie")
//parse this header
}
})
await authClient.signUp.email({}, {
onSuccess: (ctx)=>{
const setCookieHeader = ctx.response.headers.get("set-cookie")
//parse this header
}
})
Nelson
Nelson3d ago
Hello, sorry to bother. I'm wondering how to achieve the same result with social provider?
bekacru
bekacru3d ago
It's harder to test social providers unless you mock their response. In which case you can do the same thing but in /callback/:providerId path instead.
Nelson
Nelson2d ago
Thanks! But I end up using this one:
const cookie = await serializeSignedCookie(
'better-auth.session_token',
sessionToken,
env.BETTER_AUTH_SECRET
)
const cookie = await serializeSignedCookie(
'better-auth.session_token',
sessionToken,
env.BETTER_AUTH_SECRET
)

Did you find this page helpful?