使用页面对象模型时,JS跨文件调用变量报错问题咨询
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.jsfile. - Bracket Notation:
targetPage.e[elementID]lets you dynamically access a property using a string (yourelementIDparameter), which is exactly what you need when passing inAddButtonIdas 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

