Add support for options.headers in m.request + tests/docs

I also had to edit the mocks accordingly, so I could inspect the headers set.
This commit is contained in:
impinball 2016-12-30 02:52:00 -05:00
parent 00a3ce3657
commit 95d738bc71
4 changed files with 66 additions and 5 deletions

View file

@ -33,7 +33,7 @@ module.exports = function($window, Promise) {
}
return args
}
function request(args, extra) {
var finalize = finalizer()
args = normalize(args, extra)
@ -63,6 +63,10 @@ module.exports = function($window, Promise) {
}
if (args.withCredentials) xhr.withCredentials = args.withCredentials
for (var key in args.headers) if ({}.hasOwnProperty.call(args.headers, key)) {
xhr.setRequestHeader(key, args.headers[key])
}
if (typeof args.config === "function") xhr = args.config(xhr, args) || xhr
xhr.onreadystatechange = function() {
@ -93,7 +97,7 @@ module.exports = function($window, Promise) {
function jsonp(args, extra) {
var finalize = finalizer()
args = normalize(args, extra)
var promise = new Promise(function(resolve, reject) {
var callbackName = args.callbackName || "_mithril_" + Math.round(Math.random() * 1e16) + "_" + callbackCount++
var script = $window.document.createElement("script")

View file

@ -343,6 +343,43 @@ o.spec("xhr", function() {
done()
}, 20)
})
o("headers are set when header arg passed", function(done) {
mock.$defineRoutes({
"POST /item": function(request) {
return {status: 200, responseText: ""}
}
})
xhr({method: "POST", url: "/item", config: config, headers: {"Custom-Header": "Value"}}).then(done)
function config(xhr) {
o(xhr.getRequestHeader("Custom-Header")).equals("Value")
}
})
o("headers are with higher precedence than default headers", function(done) {
mock.$defineRoutes({
"POST /item": function(request) {
return {status: 200, responseText: ""}
}
})
xhr({method: "POST", url: "/item", config: config, headers: {"Content-Type": "Value"}}).then(done)
function config(xhr) {
o(xhr.getRequestHeader("Content-Type")).equals("Value")
}
})
o("json headers are set to the correct default value", function(done) {
mock.$defineRoutes({
"POST /item": function(request) {
return {status: 200, responseText: ""}
}
})
xhr({method: "POST", url: "/item", config: config}).then(done)
function config(xhr) {
o(xhr.getRequestHeader("Content-Type")).equals("application/json; charset=utf-8")
o(xhr.getRequestHeader("Accept")).equals("application/json, text/*")
}
})
})
o.spec("failure", function() {
o("rejects on server error", function(done) {