I’m facing an issue with Playwright tests. I have a separate module, db-connection.ts, for connecting and querying a PostgreSQL database using the pg
package. Here’s the relevant code in db-connection.ts:
import pg from 'pg';
import {envConfig} from "../playwright.config";
export async function connectAndQueryDatabase(query: string): Promise<any[]> {
const client = new pg.Client({
user: envConfig.DB_USERNAME,
password: "",
host: envConfig.DB_HOST,
port: parseInt(envConfig.DB_PORT, 10),
database: envConfig.DB_NAME,
});
try {
await client.connect();
const result = await client.query(query);
return result.rows;
} catch (error) {
console.error('Error connecting or querying database:', error);
throw error;
} finally {
await client.end();
}
}
In my Playwright test spec file (e.g., shopping-cart.spec.ts), I’m trying to utilize the connectAndQueryDatabase function from db-connection.ts.
import {test, expect} from "@playwright/test"
import {PageManager} from "../pages/page-manager";
import {connectAndQueryDatabase} from "../framework/db-connection";
import {DbQueries} from "../framework/db-queries";
test.describe('ShoppingCart', () => {
let pm: PageManager;
test.beforeEach(async ({page}) => {
pm = new PageManager(page);
await pm.homePage().openHomepage();
});
test.only('Verify adding multiple products to the shopping cart', async () => {
await connectAndQueryDatabase(DbQueries.deleteAllCoupons())
await pm.homePage().clickProductThumbnail(1);
});
Once I used the connectAndQueryDatabase() in my test spec, in Playwright test UI, my test spec shopping-cart.spec.ts is disappeared, and db-connection is displayed instead
Playwright test ui screenshot here
If I run the tests from the command line, I get an error stating “Error: Cannot find module ‘pg'”.
I’ve already installed the pg package using npm install pg –save. I’ve also verified the installation path. Here is all my node modules
Node modules screenshot
Could you please help me understand why the test UI is displaying db-connection.ts instead of my test spec and how to resolve the missing pg module error? Thank you so much for the help