来自 Protractor 测试的裸 HTTP 调用

2022-01-16 00:00:00 node.js angularjs protractor javascript

我的量角器测试需要一些数据设置,我想通过对正在运行的服务器进行一系列 POST 和 PUT 来实现这些设置.

My Protractor tests need some data setup which I would like to implement by making a series of POSTs and PUTs to the running server.

所以,问题是:如何从 Protractor 测试中执行裸"HTTP 调用?

So, the question is: How do you execute "bare" HTTP calls from Protractor tests?

我发现的一种方法是使用 Node Http 模块,但它有点笨拙.我想知道这些问题通常是如何解决的——量角器会暴露什么吗?使用 Http(和其他需要时的 Node 模块)是可行的方法吗?还有其他方法吗?

One way that I found is using Node Http module, but it's a bit unwieldy. I wonder how such problems are typically solved - does Protractor expose anything? Is using Http (and other Node modules when you need them) the way to go? Is there some other way?

推荐答案

另一种不依赖 Angular 的方法是在 browser.executeAsyncScriptXMLHttpRequest>.如果您需要在 Angular 加载或导航到页面之前作为测试设置的一部分进行调用,这将特别有用.

An alternate way that doesn't depend on Angular is manually creating an XMLHttpRequest inside of browser.executeAsyncScript. This is especially helpful if you need to make a call as part of the test setup, prior to Angular loading or prior to navigating to a page at all.

查看 Protractor 文档中的这个示例:

示例 #3:注入 XMLHttpRequest 并等待结果.在此示例中,注入脚本是使用函数文字指定的.使用这种格式时,函数被转换为字符串进行注入,所以它不应该引用任何未定义在被测页面范围内的符号.

Example #3: Injecting a XMLHttpRequest and waiting for the result. In this example, the inject script is specified with a function literal. When using this format, the function is converted to a string for injection, so it should not reference any symbols not defined in the scope of the page under test.

driver.executeAsyncScript(function() {
  var callback = arguments[arguments.length - 1];
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "/resource/data.json", true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      callback(xhr.responseText);
    }
  }
  xhr.send('');
}).then(function(str) {
  console.log(JSON.parse(str)['food']);
});

相关文章