来自量角器测试的裸HTTP调用 [英] Bare HTTP calls from Protractor tests
问题描述
My Protractor测试需要一些数据设置,我想通过向正在运行的服务器发送一系列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的方法是手动创建 XMLHttpRequest
在 browser.executeAsyncScript
中。如果您需要在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.
示例#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']);
});
这篇关于来自量角器测试的裸HTTP调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!