如何将 webdriverio 驱动程序传递到函数中以进行模块化设计?

How to pass webdriverio driver into functions for modular design?

我正在使用 webdriverio 与 appium 服务器通信。我正在尝试自动化 Instagram 交互。每个自动化都需要我登录和注销。所以,我正在考虑编写一个登录函数和一个注销函数。

目前,我有这样的东西:

const wdio = require("webdriverio");
const opts = {...}
const client = wdio.remote(opts)

const login = (client, username, password) => {
  return client
    .click("#log_in_button")
    .click("#login_username")
    .keys(username)
    .click("#password")
    .keys(password)
    .click("#button_text");
}

const someOtherAction = (client) => {
  // More actions performed on client
  // ...
}

client.init();
login(client, "username", "password")
  .someOtherAction(client);

这不起作用 ^^,但是以这种方式编写的相同代码有效:

client
  .init()
  .click("#log_in_button")
  .click("#login_username")
  .keys("username")
  .click("#password")
  .keys("password")
  .click("#button_text")
  .waitForExist("~Activity") // Some other actions...

我怀疑这与this设置不正确有关,我尝试查看webdriverio的源代码,但我不太明白。那么,我该如何传递驱动程序,以便我可以编写更加模块化、可用和可维护的代码?

此外,我不太明白这种命令链是如何工作的,因为 http://webdriver.io 的 api 文档没有说明函数的 return 值像 clickkeys 等调用,但是,它们似乎像 returning client 本身一样工作。如果有人也可以解释链接,那就太好了。

使用 WebdriverIO 编写测试的推荐方法是通过 PageObject 模式。有一个 example directory in the GitHub repo. It is also a good idea to check out the boilerplate section WebdriverIO 社区的人们提供了有用的入门包来快速入门。

所以我通过使登录成为一个 async 函数并 await 使操作发生来实现模块化。

const login = async (client, username, password) => {
  await client
   .click("#log_in_button")
   .click("#login_username")
   .keys(username)
   .click("#password")
   .keys(password)
   .click("#button_text");
}

然后将其用作:

const client = wdio.remote(opts);
(async() => {
  await client.init();
  await login(client, 'username', 'password');
})();