0

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

Package.json file

{
  "name": "playwrightwebautomation",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "local-test": "ENV=local npx playwright test",
    "prod-test": "ENV=prod npx playwright test"
  },
  "devDependencies": {
    "@faker-js/faker": "^7.6.0",
    "@playwright/test": "^1.45.0",
    "@types/node": "^20.14.9",
    "dotenv": "^16.4.5",
    "xlsx": "^0.18.5"
  },
  "dependencies": {
    "@types/pg": "^8.11.6"
  }
}

Playwright.config.ts file

import { defineConfig, devices } from '@playwright/test';
import dotenv from 'dotenv';

dotenv.config({
  path: `./env/.env.${process.env.ENV}`,
});

export default defineConfig({
  testDir: "./tests",
  /* Run tests in files in parallel */
  fullyParallel: true,
  /* Fail the build on CI if you accidentally left test.only in the source code. */
  forbidOnly: !!process.env.CI,
  /* Retry on CI only */
  retries: process.env.CI ? 2 : 0,
  /* Opt out of parallel tests on CI. */
  workers: process.env.CI ? 1 : undefined,
  /* Reporter to use. See https://playwright.dev/docs/test-reporters */
  reporter: 'html',
  /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
  use: {
    /* Base URL to use in actions like `await page.goto('/')`. */
    // baseURL: 'http://127.0.0.1:3000',

    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: 'on-first-retry',
    launchOptions: {
      args: ['--start-maximized']
    }
  },

  /* Configure projects for major browsers */
  projects: [
    {
      name: 'chromium',
      use: {
        viewport: null
      },
    },

    {
      name: 'chrome',
      use: {
        viewport: null
      }
    },

    {
      name: 'firefox',
      use: {
        viewport: null
      },
    },
  ],

});

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

5
  • Playwright shouldn't be testing the db directly. It's an implementation detail. Test the UI like your user would. Just asked, same answer pretty much: How can I use my own composables inside a playwright test?. Commented Jul 10, 2024 at 19:33
  • If you want integration tests for your routes down to the DB level, use jest and supertest. Playwright is slow, so there's a big performance cost to launching a whole browser for every test, and so it's a misuse of it to bypass its purpose and test something other libraries are better-suited to testing. True E2E tests test the DB transitively, by inference, whereas router integration tests can make more direct assertions on its state. Commented Jul 10, 2024 at 21:17
  • @ggorlen thanks for your answer. Actually my test framework is not for db testing. In some cases, I might want to access to database to delete test data from previous test cases or create some mock data so I'll have an accurate test data for my test. Choosing another testing tool is not an option as I have to use Playwright for my project Commented Jul 13, 2024 at 14:22
  • Fair enough. I'm guessing the db file is being seen as a test due to your testMatch config. Make sure it's default or only matches test files. Assuming the paths are correct, the module should be found. I suggest posting your full config, package.json, exact commands you're running, and a file tree. Commented Jul 13, 2024 at 14:23
  • Hi @ggorlen , I just added my package.json and playwright.config.ts file. Any ideas what might be causing the error? Commented Jul 13, 2024 at 15:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.