Playwright报错:Cannot read properties of undefined (reading 'page') 求助
解决Playwright中动态函数调用时
this.page未定义的问题 问题根源
你把onePhaseAction.getDesignTypeSeries直接传给doSelectOption时,这个函数的this上下文丢失了——执行getElement()的时候,this不再指向OnePhaseAction的实例,自然读不到this.page,所以抛出cannot read properties of undefined (reading 'page')错误。
三种修复方法
1. 绑定this上下文
调用doSelectOption时,用bind把函数的this绑定到实例上:
test('1-Phase-Check validation rule: Size', async ({page}) => { const onePhaseAction = new OnePhaseAction(page) await onePhaseAction.doSelectOption( onePhaseAction.getDesignTypeSeries.bind(onePhaseAction), eng.TYPE_SERIES.PED, ) })
2. 箭头函数包裹
用箭头函数包裹原方法调用,箭头函数会继承外层的this上下文:
test('1-Phase-Check validation rule: Size', async ({page}) => { const onePhaseAction = new OnePhaseAction(page) await onePhaseAction.doSelectOption( () => onePhaseAction.getDesignTypeSeries(), eng.TYPE_SERIES.PED, ) })
3. 把类方法改成箭头函数
在OnePhaseAction类里,把getDesignTypeSeries定义成箭头函数,这样它的this会永久绑定到类实例:
export class OnePhaseAction{ public page: Page constructor(page: Page) { this.page = page } getDesignTypeSeries = () => { return this.page.locator(selector.select_DesignTypeSeries) } 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() } }
效果验证
随便选一种方法改完后,getElement()执行时就能正确拿到this.page,下拉选择的逻辑就能正常运行了。
内容的提问来源于stack exchange,提问作者clark
相关产品推荐
相关产品推荐

