playwright and using files in subdirectories

Viewed 1011

I'm trying to create a playwright test (in javascript) that uses the page object model of classes, but where the test and page object model aren't in the same directory path.

The problem I'm having is it can't find my page-object-model class file. The error is Error: Cannot find module './pom/home-page'. What am I missing or doing wrong?

My file setup and path structure are as follows:

/package.config.js

...
const config = {
   testDir: './test/playwright',
...

/test/playwright/pom/home-page.js

const { expect } = require ('@playwright/test');

exports.HomePage = class HomePage {
   constructor(page) {
      this.page = page;
      this.searchInput = page.locator('#searchInput');
      this.searchButton = page.locator('#searchButton');
   }
}

/test/playwright/scripts/home/search.spec.js

const {test, expect} = require('@playwright/test');
const {HomePage} = require('./pom/home-page');

test.beforeAll( async ({ page }) => { ... });
test.beforeEach( async ({ page }) => { ... });
test.afterAll( async ({ page }) => { ... });
test.describe( 'As a user I want to search', () => {
   test('"mySearchTerm1" and return {the expected result}', async ({ page }) => {
      const homePage = new HomePage(page); 
      ...
   });

   test('"mySearchTerm2" and return {the expected result}', async ({ page }) => {
      const homePage = new HomePage(page); 
      ...
   });
});
2 Answers

So, apparently the file reference is relative to the directory the test is located, not the testDir directory defined in the config file. I need to change line 2 in search.spec.js

const {HomePage} = require('../../pom/home-page');
Related