如何在页面部分嵌套nightwatch.js命令?

时间:2018-06-01 22:02:41

标签: javascript testing nightwatch.js

我有一个页面pages/login.js看起来像:

function fillAndSubmitLogin(email, password) {
  return this
  .waitForElementVisible('@emailInput')
  .setValue('@emailInput', email)
  .setValue('@passwordInput', password)
  .waitForElementVisible('@loginSubmitButton')
  .click('@loginSubmitButton');
}


export default {
  commands: [
    fillAndSubmitLogin
  ],
  elements: {
    emailInput: 'input#email',
    passwordInput: 'input[type=password]',
    TFAInput: 'input#token',
    loginSubmitButton: '.form-actions button.btn.btn-danger'
  }
};

我有另一页pages/hompage.js主页.js尝试将pages/login.js作为一个部分

import login from "./login.js";

module.exports = {
  url: 'http://localhost:2001',
  sections: {
    login: {
      selector: 'div.login-wrapper',
      ...login
    }
  }
};

然后我有一个尝试登录hompage部分的测试用例

  'Homepage Users can login': (client) => {
    const homepage = client.page.homepage();
    homepage
    .navigate()
    .expect.section('@login').to.be.visible;


    const login = homepage.section.login;
    login
    .fillAndSubmitLogin('user@test.com', 'password');

    client.end();
  }

此测试失败并出现以下错误

TypeError: login.fillAndSubmitLogin is not a function
       at Object.Homepage Users can login (/Users/kevzettler//frontend/test/nightwatch/specs/homepage.spec.js:32:6)
       at <anonymous>
       at process._tickCallback (internal/process/next_tick.js:182:7)

  login.fillAndSubmitLogin is not a function
       at Object.Homepage Users can login (/Users/kevzettler//frontend/test/nightwatch/specs/homepage.spec.js:32:6)
       at <anonymous>
       at process._tickCallback (internal/process/next_tick.js:182:7)

1 个答案:

答案 0 :(得分:4)

根据Nightwatch docs,在页面对象中导出的任何命令都应该是纯JavaScript对象,其中键是命令名,值是函数。例如:

var googleCommands = {
  submit: function() {
    this.api.pause(1000);
    return this.waitForElementVisible('@submitButton', 1000)
      .click('@submitButton')
      .waitForElementNotPresent('@submitButton');
  }
};

module.exports = {
  commands: [googleCommands],
  elements: //...etc ...
  // etc...
}

在此示例中,模块导出googleCommands,这是一个具有键( submit )和相应函数的命令对象。我相信你应该重构你的代码如下:

function fillAndSubmitLogin = {
  fillAndSubmitLogin: function(email, password) {
    return this
    .waitForElementVisible('@emailInput')
    .setValue('@emailInput', email)
    .setValue('@passwordInput', password)
    .waitForElementVisible('@loginSubmitButton')
    .click('@loginSubmitButton');
  }
};

当然,您不必在两个地方都使命令名称相同(如示例所示(googleCommands / submit)。这允许您公开各种功能一个command。希望回答这个问题!