How to use $lib & $env aliases from SvelteKit in Playwright?
Asked Answered
B

2

6

I want to insert in database some data. My database connector is using DrizzleORM in a file named db.ts

src/lib/server/db.ts

import { connect } from "@planetscale/database";
import { drizzle } from "drizzle-orm/planetscale-serverless";
import { DB_HOST, DB_PASSWORD, DB_USERNAME } from "$env/static/private";

const connection = connect({
  host: DB_HOST,
  username: DB_USERNAME,
  password: DB_PASSWORD,
});

export const db = drizzle(connection);

now I want to use the declared object db in playwright. But once i do I get the following error :

Error: Cannot find package '$env' imported from [...]\src\lib\server\db.ts

I've tried to use aliases in the tsconfig.json like so :

{
    "extends": "./.svelte-kit/tsconfig.json",
    "compilerOptions": {
        [...]
        "baseUrl": ".",
        "paths": {
            "$lib": [
                "./src/lib"
            ],
            "$lib/*": [
                "./src/lib/*"
            ],
            "$env/*": ["tests/e2e/mocks/env/*"]
        },
    }
}

but this is not working.

Bearnard answered 18/10, 2023 at 7:50 Comment(1)
"$env/static/private" cannot be used client-side, so you don't import the db.ts file in any of your Svelte components, right?Physique
B
1

Workaround

import { connect } from "@planetscale/database";
import { drizzle } from "drizzle-orm/planetscale-serverless";
import 'dotenv/config'

var DB_HOST = process.env.DB_HOST
var DB_PASSWORD = process.env.DB_PASSWORD
var DB_USERNAME = process.env.DB_USERNAME

const connection = connect({
  host: DB_HOST,
  username: DB_USERNAME,
  password: DB_PASSWORD,
});

export const db = drizzle(connection);

import .env variables from npm module dotenv

Bearnard answered 18/10, 2023 at 11:34 Comment(0)
T
0

I think the easiest one would be to mock it.

Vitest version:

vi.mock('$env/static/private', () => import.meta.env);

Playwright version:

(async () => {
  const browser = await webkit.launch({ headless: false });
  const context = await browser.newContext();
  const page = await context.newPage();
  // this should expose the SvelteKit binding.
  await page.exposeBinding('$env/static/private', ({ page }) => process.env);
...
Troubadour answered 23/1 at 6:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.