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

349 views Asked by At

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.

2

There are 2 answers

0
Sowdowdow On

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

0
DeveloperMindset.com On

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);
...