【问题标题】:How do you call an external API from Selenium script to populate a field using Node JS?如何从 Selenium 脚本调用外部 API 以使用 Node JS 填充字段?
【发布时间】:2021-05-14 10:05:35
【问题描述】:

我有一个用例,我需要调用外部 API、解析返回的 JSON 并在网页中填充表单字段,所有这些都在使用 Node JS 编写的 Selenium 脚本中。

类似这样的:

// in Selenium script get the form field
let inputElement = await getElementById(driver, "my-id");
// then call an API including callback function

// in the callback function with the JSON response from the API
const myText = response.data.text;
await inputElement.sendKeys(myText,Key.ENTER);

实际上我什至不知道从哪里开始 - 因为我将向作为 Selenium 脚本的一部分运行的现有异步代码添加异步代码(API 调用并等待回调中的响应)。而且我不需要丢失对 Web 驱动程序和输入元素的引用。

一些让我前进的建议和建议会非常有帮助。

【问题讨论】:

  • 我不确定node.js,但如果这是在Java中,我会使用Maven作为构建工具和用于api回调的restAssured库和用于json解析的JSONObject。
  • 我可以假设您熟悉 nodejs https 包吗?这可以很好地用于发出您想要的任何请求,将数据包含为回调等。
  • @cruisepandey 有一种伪restassured npm package,但我没有使用过自己,所以我不能保证。

标签: node.js api selenium testing automation


【解决方案1】:

如果你使用节点的内置 https 模块,你可以做这样的事情..

const { Builder, By, Key, until } = require("selenium-webdriver");
const https = require("https");

(async function example() {
  let driver = await new Builder().forBrowser("chrome").build();
  try {
    await driver.get("http://www.google.com/ncr");
    await https.get("https://jsonplaceholder.typicode.com/users/1", (resp) => {
      let data = "";
      resp.on("data", (chunk) => {
        data += chunk;
      });
      resp.on("end", async () => {
        // console.log(JSON.parse(data)["name"]);
        await driver
          .findElement(By.name("q"))
          .sendKeys(JSON.parse(data)["name"], Key.RETURN);
      });
    });
    await driver.wait(until.titleContains("- Google Search"), 1000);
  } finally {
    await driver.quit();
  }
})();

或者如果你已经在使用像 axios 这样的库,那么你可以这样做

const { Builder, By, Key, until } = require("selenium-webdriver");
const axios = require("axios");
(async function example() {
  let driver = await new Builder().forBrowser("chrome").build();
  try {
    await driver.get("http://www.google.com/ncr");
    const { data } = await axios.get(
      "https://jsonplaceholder.typicode.com/users/1"
    );
    await driver.findElement(By.name("q")).sendKeys(data["name"], Key.RETURN);
    await driver.wait(until.titleContains("- Google Search"), 1000);
  } finally {
    await driver.quit();
  }
})();

希望这是您正在寻找的..

【讨论】:

  • Bharateesh - 看起来很棒 - 谢谢。只是检查 - 但驱动程序的变量范围是否足够?驱动程序在 API 回调之外声明,然后在 API 回调函数的范围内使用。驱动程序变量范围有效吗?
  • 嗨@MountainMan,抱歉回复晚了。。是的,范围很好,驱动范围绑定到这里的函数示例,所以你可以在任何地方使用它,只要你在这个方法..
猜你喜欢
  • 1970-01-01
  • 2019-10-26
  • 2023-03-23
  • 2020-06-07
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 2018-03-25
  • 1970-01-01
相关资源
最近更新 更多