問(wèn)題描述
我的量角器測(cè)試需要一些數(shù)據(jù)設(shè)置,我想通過(guò)對(duì)正在運(yùn)行的服務(wù)器進(jìn)行一系列 POST 和 PUT 來(lái)實(shí)現(xiàn)這些設(shè)置.
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.
所以,問(wèn)題是:如何從 Protractor 測(cè)試中執(zhí)行裸"HTTP 調(diào)用?
So, the question is: How do you execute "bare" HTTP calls from Protractor tests?
我發(fā)現(xiàn)的一種方法是使用 Node Http 模塊,但它有點(diǎn)笨拙.我想知道這些問(wèn)題通常是如何解決的——量角器會(huì)暴露什么嗎?使用 Http(和其他需要時(shí)的 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?
推薦答案
另一種不依賴(lài) Angular 的方法是在 browser.executeAsyncScript
XMLHttpRequest>.如果您需要在 Angular 加載或?qū)Ш降巾?yè)面之前作為測(cè)試設(shè)置的一部分進(jìn)行調(diào)用,這將特別有用.
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 文檔中的這個(gè)示例:
示例 #3:注入 XMLHttpRequest 并等待結(jié)果.在此示例中,注入腳本是使用函數(shù)文字指定的.使用這種格式時(shí),函數(shù)被轉(zhuǎn)換為字符串進(jìn)行注入,所以它不應(yīng)該引用任何未定義在被測(cè)頁(yè)面范圍內(nèi)的符號(hào).
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']);
});
這篇關(guān)于來(lái)自 Protractor 測(cè)試的裸 HTTP 調(diào)用的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!