Using Page Objects

To use Page Objects, we will need to create a separate JS file for each page. We need to specify the folder that contains these page files in the configuration file. The following is the change we make to nightwatch.conf.js:

module.exports = {
...
page_objects_path: 'tests/e2e/page-objects',
...
}

The following is the Page Object for the login page, tests/e2e/page-objects/LoginPage.js:

module.exports = {
url: function () {
return this.api.launchUrl + '/login'
},
elements: {
app: '#app',
logoImage: 'img.logo',
usernameInput: '#username',
passwordInput: '#password',
submitButton: 'button[type=submit]',
formError: '.failed'
},
commands: [{
login: function (username, password) {
this
.setValue('@usernameInput', username)
.setValue('@passwordInput', password)
.click('@submitButton')
}
}]
}

As you can see, this Page Object has three parts: url, elements, and commands. url is used to specify the page's URL. The elements object is a definition of the named page elements with CSS selectors. The commands array contains the behavior this page supports. In our case, it is login. To use a Page Object, we will call browser.page.<PageObjectFileName>(), as follows:

module.exports = {
'login page renders elements': function (browser) {
const loginPage = browser.page.LoginPage()
loginPage
.navigate()
.waitForElementVisible('@app', 500)
.assert.visible('@usernameInput')
.assert.visible('@passwordInput')
.assert.visible('@submitButton')
.assert.hidden('@formError')

browser.end()
},
...
}

As you can see, once the loginPage constant is ready, we call its navigate() method to go to the login page and then do assertions. Once that is done, we call browser.end(). This test only verifies that the page is rendered correctly. The following shows how to make a login request:

'login with email address': function (browser) {
const loginPage = browser.page.LoginPage()
const homePage = browser.page.HomePage()
loginPage
.navigate()
.login(data.emailAddress, data.password)

browser.pause(500)

homePage
.navigate()
.expect.element('@pageTitle').text.to.contain('Home Page')

browser.end()
}

As you can see, after navigating to the login page, we simply call the login() command defined in the Page Object. Once that is done, we wait for half a second and then navigate to the home page and check the page title on that page to verify the login has succeeded. Due to the scope, we won't list all the details here. You can find them in the commit record.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.9.148