从Protractor迁移至Playwright:无法访问AngularJS Scope求助
解决Playwright中访问AngularJS Scope的问题
先修正代码中的语法错误
你当前代码里有个变量名错误:scope.$ctrl[myFunction]() 应该改为 scope.$ctrl[functionName](),否则会因为myFunction未定义报错。
常见问题及解决办法
1. AngularJS debugInfo未开启(最常见原因)
AngularJS 1.3+ 默认关闭了debugInfo,这会导致scope()方法无法获取到作用域。可以通过以下方式开启:
方式一:运行时临时开启
在执行获取scope的代码前,先执行:
await this.page.evaluate(() => { (window as any).angular.reloadWithDebugInfo(); });
方式二:在应用配置中开启(适合测试环境)
如果有权限修改测试环境的应用代码,在模块配置中开启:
angular.module('yourAppModule').config(['$compileProvider', function($compileProvider) { $compileProvider.debugInfoEnabled(true); }]);
2. 使用isolateScope()替代scope()
如果你的元素是AngularJS组件(或使用隔离作用域的指令),直接调用scope()会获取到父作用域,而非组件自身的隔离作用域。此时应该优先使用isolateScope():
const elementHandle: ElementHandle | null = await this.button.elementHandle(); await this.page.evaluate( ({ element, functionName }) => { const angularElement = (window as any).angular.element(element); // 优先获取隔离作用域, fallback到普通作用域 const scope = angularElement.isolateScope() || angularElement.scope(); if (!scope) { throw new Error('无法获取元素的AngularJS作用域'); } scope.$ctrl[functionName](); }, { element: elementHandle, functionName } );
3. 确认元素属于AngularJS上下文
确保你获取的元素确实被AngularJS管理,可以先检查元素是否带有ng-scope类:
const hasNgScope = await this.page.evaluate((element) => { return element.classList.contains('ng-scope'); }, elementHandle); if (!hasNgScope) { console.error('该元素不在AngularJS作用域范围内'); }
内容的提问来源于stack exchange,提问作者fqdr
相关产品推荐
相关产品推荐

