You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用页面对象模型时,JS跨文件调用变量报错问题咨询

Fixing Dynamic Page Object Property Access in Protractor

The core issue here is that you're trying to access object properties by concatenating strings (like pageName+".e.url"), which just creates a string literal instead of resolving to the actual value from your page module. JavaScript doesn't automatically evaluate those strings as object references—you need to use proper module importing and bracket notation for dynamic property access.

Step 1: Set Up a Page Module Lookup

First, you'll want to import your page modules and create a way to reference them by name. Instead of passing just a string pageName, map the name to the actual imported module.

For example, if you have multiple page files (like page.js, otherPage.js), create a lookup object:

// Import your page modules
const page = require('./page.js');
const otherPage = require('./otherPage.js');

// Create a page lookup map
const pages = {
  page: page,
  otherPage: otherPage
};

Step 2: Fix the urlCall Function

Now, use the lookup map to get the correct page module, then access its e.url property directly:

urlCall: function(pageName) {
  const targetPage = pages[pageName];
  if (!targetPage) {
    throw new Error(`Page ${pageName} not found in page lookup`);
  }
  return browser.get(targetPage.e.url);
}

Step 3: Fix the clickButton Function

Similarly, use bracket notation to dynamically access the element ID from the page's e object. Concatenating strings won't work here—instead, use targetPage.e[elementID] to get the actual ID value:

clickButton: function(pageName, elementID) {
  const targetPage = pages[pageName];
  if (!targetPage || !targetPage.e[elementID]) {
    throw new Error(`Element ${elementID} not found on page ${pageName}`);
  }
  const buttonId = targetPage.e[elementID];
  element(by.id(buttonId)).click();
}

Why This Works

  • Module Importing: By importing your page modules and storing them in a lookup map, you have direct references to the objects exported from each page.js file.
  • Bracket Notation: targetPage.e[elementID] lets you dynamically access a property using a string (your elementID parameter), which is exactly what you need when passing in AddButtonId as the element ID.

Example Usage

Now you can call your functions like this, and they'll correctly resolve to the page's URL and element ID:

// Navigate to the page
urlCall('page');

// Click the add button
clickButton('page', 'AddButtonId');

This approach keeps your Page Object Model clean and avoids the string concatenation issue that was breaking your property access.

内容的提问来源于stack exchange,提问作者Rudolf Coutinho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:49:36