在Nightwatch中使用page-object命令中的函数

时间:2017-04-05 13:32:05

标签: javascript nightwatch.js e2e-testing

忽略selectUser功能的展示位置。我还在尝试玩它。如何在页面对象commands中使用函数?在每个命令功能内部重复该功能5次之前,但为了清洁,显然需要更改,我无法弄清楚如何。

Page-object片段:

var selectUser = function(userName, password) {
  return this.waitForElementVisible('@usernameField')
    .setValue('@usernameField', userName)
    .setValue('@passwordField', password)
    .click('@signOnButton')
    .waitForElementVisible('@eventTaskManager');
};

module.exports = {
  elements: {
    usernameField: '#UserName',
    passwordField: '#Password',
    signOnButton: 'input[value="Sign On"]',
    cancelButton: 'a[href$="/cancel"]',
    errorMessage: '.icon-warning',
    eventTaskManager: '.concierge'
  },

  commands: [{
    signInAsUniregisteredUser: function() {
      selectUser(unregisteredUserName, unregisteredUserPass);
    },

    signInAsRegisteredUser: function() {
      selectUser(registeredUserName, prodRegisteredPass);
    },

    signInAsUnregisteredUser_Regression: function() {
      selectUser(unregisteredUserName, unregisteredUserPass);
    },

    signInAsRegisteredUser_Regression: function() {
      selectUser(registeredUserName, prodRegisteredPass);
    },

    signInAsRegisteredUser_Production: function() {
      selectUser(prodRegisteredUser, prodRegisteredPass);
    }
  }]
};

1 个答案:

答案 0 :(得分:1)

首先,对于登录功能,只有2个断言登录" ok"或登录"失败" (未注册,错误的凭据,缺少用户名,......),因此您只需要这个页面对象。

    var pageCommands = {
    tryToLogin: function(userName, password) {
        return this.waitForElementVisible('@usernameField')
            .setValue('@usernameField', userName)
            .setValue('@passwordField', password)
            .click('@signOnButton');
    },
    assertLoginSuccesfully: function() {
        return this.waitForElementVisible('@eventTaskManager'); // login pass    
    },
    assertLoginUnSuccesfully: function() {
        return this.waitForElementVisible('@errorMessage'); // login fail 
    }
};

module.exports = {
    elements: {
        usernameField: '#UserName',
        passwordField: '#Password',
        signOnButton: 'input[value="Sign On"]',
        cancelButton: 'a[href$="/cancel"]',
        errorMessage: '.icon-warning',
        eventTaskManager: '.concierge'
    },

    commands: [pageCommands],
};

在你的测试用例中:

const loginPage = browser.page.login();
const dataForTest = require('./data.json');
const credentials = { 
   username : dataForTest.username , 
   password : dataForTest.password
};

login.tryToLogin(credentials.username,credentials.password)
     .assertLoginSuccesfully() // if data from dataForTest is correct

通过将所有内容存储在data.json(或任何您想要的任何内容)中,这种做法可以让您远离硬值。