Skip to content

Commit

Permalink
Throw a TypeError if Request or Response functions are called without…
Browse files Browse the repository at this point in the history
… `new`
  • Loading branch information
JakeChampion committed Jul 9, 2020
1 parent e329852 commit 5ef028d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
7 changes: 7 additions & 0 deletions fetch.js
Expand Up @@ -322,6 +322,10 @@ function normalizeMethod(method) {
}

export function Request(input, options) {
if (!(this instanceof Request)) {
throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.')
}

options = options || {}
var body = options.body

Expand Down Expand Up @@ -414,6 +418,9 @@ function parseHeaders(rawHeaders) {
Body.call(Request.prototype)

export function Response(bodyInit, options) {
if (!(this instanceof Response)) {
throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.')
}
if (!options) {
options = {}
}
Expand Down
10 changes: 10 additions & 0 deletions test/test.js
Expand Up @@ -330,6 +330,11 @@ exercise.forEach(function(exerciseMode) {

// https://fetch.spec.whatwg.org/#request-class
suite('Request', function() {
test('called as normal function', function() {
assert.throws(function() {
Request('https://fetch.spec.whatwg.org/')
})
})
test('construct with string url', function() {
var request = new Request('https://fetch.spec.whatwg.org/')
assert.equal(request.url, 'https://fetch.spec.whatwg.org/')
Expand Down Expand Up @@ -612,6 +617,11 @@ exercise.forEach(function(exerciseMode) {
return new Response(body)
})

test('called as normal function', function() {
assert.throws(function() {
Response('{"foo":"bar"}', {headers: {'content-type': 'application/json'}})
})
})
test('creates Headers object from raw headers', function() {
var r = new Response('{"foo":"bar"}', {headers: {'content-type': 'application/json'}})
assert.equal(r.headers instanceof Headers, true)
Expand Down

0 comments on commit 5ef028d

Please sign in to comment.