使用Protractor时是否需要在Spec文件中初始化页面对象?
Do I need to initialize Page Objects in Protractor Spec files?
First, let's look at your current implementation:
当前我采用的是如下风格的简易页面对象模型:
var loginPage = require('../pages/loginPage'); var homePage = require('../pages/homePage'); describe('Login', function () { it('Valid Login should successfully reach the home page, with valid page title.', function () { browser.driver.get("https://dev.mysite.com/"); loginPage.login('TestUser', 'TestPassword'); homePage.getHeaderText(); //expect header text to equal "My header" }); });
To answer your question clearly: No, you don't need to manually initialize page objects in your Spec files—and your current code is actually aligned with Protractor's official style guide recommendations.
Here's the breakdown:
- The standard page object pattern in Protractor expects your page modules to export a ready-to-use instance of the page object, not just a constructor. This means the initialization work happens inside the page module itself, not in your test specs.
- For example, your
loginPage.jsis likely structured in the official preferred way:
// loginPage.js function LoginPage() { this.usernameInput = element(by.id('username')); this.passwordInput = element(by.id('password')); this.loginButton = element(by.id('login-btn')); this.login = function(username, password) { this.usernameInput.sendKeys(username); this.passwordInput.sendKeys(password); this.loginButton.click(); }; } // Export an already-instantiated object ready for use module.exports = new LoginPage();
- If you're using ES6 classes, the pattern stays consistent—export an instance directly from the module:
// loginPage.js class LoginPage { constructor() { this.usernameInput = element(by.id('username')); this.passwordInput = element(by.id('password')); this.loginButton = element(by.id('login-btn')); } login(username, password) { this.usernameInput.sendKeys(username); this.passwordInput.sendKeys(password); this.loginButton.click(); } } module.exports = new LoginPage();
- There is an alternative approach where you export the constructor and initialize it in the Spec, but this is not the official recommended practice. It adds unnecessary boilerplate to your tests and can lead to redundant element lookups if you instantiate the page object multiple times.
In short: Stick with your current approach. By requiring the page modules directly, you're using page objects exactly as the Protractor style guide intends—no extra initialization steps are needed in your specs.
内容的提问来源于stack exchange,提问作者dsidler
相关产品推荐
相关产品推荐

