如何使用实习生测试框架正确设计页面对象

How to correctly design page objects using theintern testing framework

本文关键字:面对 对象 何使用 实习生 测试 框架      更新时间:2023-09-26

我正在使用实习生框架创建功能测试。我想使用"页面对象"对我的测试进行建模,因为我希望代码是可重用的。

在原始文档中,有一个非常简化的示例,演示如何使用一个名为"login"的方法创建页面对象。
在此示例中,此方法的所有逻辑都在方法本身内部。

我想创建一个页面对象,

该对象表示比登录页面稍微复杂的页面,并能够重用页面内的组件以进行不同的操作。

这是我想做的一个例子:

// in tests/support/pages/IndexPage.js
define(function (require) {
  // the page object is created as a constructor
  // so we can provide the remote Command object
  // at runtime
  function IndexPage(remote) {
    this.remote = remote;
  }
  function enterUsername(username) {
    return this.remote
      .findById('login').click().type(username).end();
  }
  function enterPassword(pass) {
    return this.remote
      .findById('password').click().type(pass).end();
  }
  IndexPage.prototype = {
    constructor: IndexPage,
    // the login function accepts username and password
    // and returns a promise that resolves to `true` on
    // success or rejects with an error on failure
    login: function (username, password) {
      return this
        .enterUsername(username)
        .enterPassword(password)
        .findById('loginButton')
        .click()
        .end()
        // then, we verify the success of the action by
        // looking for a login success marker on the page
        .setFindTimeout(5000)
        .findById('loginSuccess')
        .then(function () {
          // if it succeeds, resolve to `true`; otherwise
          // allow the error from whichever previous
          // operation failed to reject the final promise
          return true;
        });
    },
    // …additional page interaction tasks…
  };
  return IndexPage;
});

请注意我是如何创建enterUsernameenterPassword方法的。
这是因为我想在同一页面对象的其他测试中重用这些方法。这样做的问题是我无法链接这些方法,它不起作用。

可以链接的方法都返回Command对象,但是当我链接我的方法时,它们没有在Command方法上定义,因此调用第一个方法(在我的示例中这是enterUsername),但随后第二个失败,显然是因为enterPassword没有在Command对象上定义。

我想知道如何对页面对象进行建模,以便我可以在页面对象中重用部分代码,但仍然具有像这样流畅的语法。

提前致谢:)

最简单的

解决方案是将方法用作then回调处理程序,例如:

function enterName(username) {
    return function () {
        return this.parent.findById('login').click().type(username);
    }
}
function enterPassword(password) {
    return function () {
        return this.parent.findById('password').click().type(pass).end();
    }
}
IndexPage.prototype = {
    constructor: IndexPage,
    login: function (username, password) {
        return this.remote
            .then(enterUsername(username))
            .then(enterPassword(password))
            .findById('loginButton')
            // ...
    }
}