Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Throw a TypeError if Request or Response functions are called without new #796

Merged
merged 2 commits into from
Jul 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions fetch.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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