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

How to nest nightwatch.js commands in page sections?

我有一个页面 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 homepage.js 尝试将 pages/login.js 作为一个部分包含

import login from "./login.js";

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

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

  '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)

根据 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。希望能回答问题!