我有一个CasperJS的测试步骤,它执行以下操作:
this.fillSelectors("#registration-form", {
"#first-name": "Bob",
"#last-name": "Smith",
"#email-address": RANDOM_EMAIL,
"#password": PASSWORD,
"#password-confirm": PASSWORD
}, true);
我希望能够发送HTTP标头。我似乎无法在没有"手动"的情况下找到一种方法。发布表单,这不是我想要的那种测试。
答案 0 :(得分:6)
比下面的方法更简单。您可以访问PhantomJS网页实例的casper.page.customHeaders
属性。
casper.then(function() {
casper.page.customHeaders = {
"CuStOm": "Header"
}; // set headers
this.fillSelectors("#registration-form", { /*...*/ }, true);
});
casper.then(function() {
casper.page.customHeaders = {}; // reset headers
});
问题是此方法会将自定义标头添加到每个请求,直到再次禁用它为止。您可以尝试根据setTimeout
或直接在fillSelectors
后面重置标头。
您在浏览器中cannot set headers for a form submission。 __utils__.sendAJAX
也不提供自定义标题。
您需要使用XMLHttpRequest发送请求。以下函数替换表单的提交处理程序以发送Ajax调用,并等待:
casper.thenFormToXHR = function(formSelector, data, customHeaders){
this.thenEvaluate(function(formSelector, customHeaders){
// see https://stackoverflow.com/a/19838177/1816580
function submitForm(oFormElement) {
window.__requestDone = false;
var xhr = new XMLHttpRequest();
for(var header in customHeaders) {
xhr.setRequestHeader(header, customHeaders[header]);
}
xhr.onload = function(){
window.__requestDone = true;
};
xhr.open (oFormElement.method, oFormElement.action, true);
xhr.send (new FormData(oFormElement));
return false;
}
document.querySelector(formSelector).onsubmit = submitForm;
}, formSelector, customHeaders);
this.then(function(){
this.fillSelectors(formSelector, data, true);
});
this.waitFor(function check(){
return this.evaluate(function(){
return window.__requestDone;
});
});
};
然后您可以这样调用:
casper.thenFormToXHR("#registration-form", {
"#first-name": "Bob",
"#last-name": "Smith",
"#email-address": RANDOM_EMAIL,
"#password": PASSWORD,
"#password-confirm": PASSWORD
}, {
"X-Requested-With": "XMLHttpRequest" // here should be your custom headers
});
如果您不需要等待XHR完成,可以减少代码:
casper.formToXHR = function(formSelector, data, customHeaders){
this.evaluate(function(formSelector, customHeaders){
// see https://stackoverflow.com/a/19838177/1816580
function submitForm(oFormElement) {
var xhr = new XMLHttpRequest();
for(var header in customHeaders) {
xhr.setRequestHeader(header, customHeaders[header]);
}
xhr.open (oFormElement.method, oFormElement.action, true);
xhr.send (new FormData(oFormElement));
return false;
}
document.querySelector(formSelector).onsubmit = submitForm;
}, formSelector, customHeaders);
this.fillSelectors(formSelector, data, true);
};