From 152a88efeec1b71cc8f9e3ddbcadff027e5323ac Mon Sep 17 00:00:00 2001 From: falsandtru Date: Fri, 8 Sep 2023 23:02:02 +0900 Subject: [PATCH] Fix FakeXMLHttpRequest --- CHANGELOG.md | 4 ++++ src/lib/xhr.ts | 49 +++++++++++++++++++++++++++---------------------- 2 files changed, 31 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e7148b1..3ede5ebf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 3.40.3 + +- Fix FakeXMLHttpRequest. + ## 3.40.2 - Fix URL processing. diff --git a/src/lib/xhr.ts b/src/lib/xhr.ts index e2127b56..36b0006a 100644 --- a/src/lib/xhr.ts +++ b/src/lib/xhr.ts @@ -6,6 +6,7 @@ export class FakeXMLHttpRequest extends XMLHttpRequest { AtomicPromise.resolve(response) .then( response => { + if (xhr.readyState === 4) return; Object.defineProperties(xhr, { responseURL: { value: url, @@ -17,10 +18,11 @@ export class FakeXMLHttpRequest extends XMLHttpRequest { xhr.send(); }, reason => { + if (xhr.readyState === 4) return; const response = reason instanceof Response ? reason : new Response(null, xhr); - Object.defineProperties(this, { + Object.defineProperties(xhr, { responseURL: { value: url, }, @@ -43,48 +45,51 @@ export class FakeXMLHttpRequest extends XMLHttpRequest { this.responseType = 'document'; } public override send(_?: Document | XMLHttpRequestBodyInit | null | undefined): void { - let state = 3; + if (this.readyState === 4) return; Object.defineProperties(this, { readyState: { - get: () => state, + configurable: true, + value: 3, }, }); + this.dispatchEvent(new ProgressEvent('loadstart')); setTimeout(() => { + if (this.readyState === 4) return; Object.defineProperties(this, { - status: { - value: 200, - }, - statusText: { - value: 'OK', - }, response: { get: () => this.responseType === 'document' ? this.responseXML : this.responseText, }, - }); - this.dispatchEvent(new ProgressEvent('loadstart')); - state = 4; - this.dispatchEvent(new ProgressEvent('loadend')); - this.dispatchEvent(new ProgressEvent('load')); - }); - } - public override abort(): void { - setTimeout(() => { - Object.defineProperties(this, { readyState: { value: 4, }, status: { - value: 400, + value: 200, }, statusText: { - value: 'Bad Request', + value: 'OK', }, }); - this.dispatchEvent(new ProgressEvent('abort')); + this.dispatchEvent(new ProgressEvent('loadend')); + this.dispatchEvent(new ProgressEvent('load')); + }); + } + public override abort(): void { + if (this.readyState === 4) return; + Object.defineProperties(this, { + readyState: { + value: 4, + }, + status: { + value: 400, + }, + statusText: { + value: 'Bad Request', + }, }); + this.dispatchEvent(new ProgressEvent('abort')); } public override getResponseHeader(name: string): string | null { switch (name.toLowerCase()) {