Search code examples
typescriptplaywright

Playwright:TypeError: Cannot read properties of undefined (reading 'page')


playwright: I got the error cannot read properties of undefined (reading 'page') in this line of code: this.page.locator(selector.select_DesignTypeSeries,) when try to build dynamic fn

I got stuck in this one few days since it always failed when doSelectOption sends dynamic fn for const element. if I send a static locator for element then it will run through the code

in test.spec.ts file:

test('1-Phase-Check validation rule: Size', async ({page}) => {
        const onePhaseAction = new OnePhaseAction(page)
       await onePhaseAction.doSelectOption(
            onePhaseAction.getDesignTypeSeries,
            eng.TYPE_SERIES.PED,
        )
})

one-phase-action.ts file:

export class OnePhaseAction{
public page: Page
    constructor(page: Page) {
        this.page = page
    }
async doSelectOption(getElement: () => Locator, type: string | number) {
        const element = getElement()
        await element.click()

        const dropdownOpenLocator = element.locator(selector.dropdown_open)
        const filteredElements = dropdownOpenLocator
            .filter({hasNot: this.page.locator('[aria-disabled]')})
            .getByText(type.toString())
            .first()

        await filteredElements.click()
    }
getDesignTypeSeries() {
        return this.page.locator(selector.select_DesignTypeSeries,)
    }
}

enter image description here

if I replace getElement() by this.page.locator(selectElemt) then its work


Solution

  • Try adding this to the constructor:

    this.getDesignTypeSeries = this.getDesignTypeSeries.bind(this);