Skip to content

Commit adb4890

Browse files
committed
fix: suppress network requests when blocked
see #181
1 parent 9920be7 commit adb4890

File tree

3 files changed

+41
-7
lines changed

3 files changed

+41
-7
lines changed

src/Network.ts

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -109,14 +109,23 @@ export default class Network {
109109
}
110110
}
111111
}
112-
xhr.open(method, url, true)
113-
xhr.setRequestHeader('Content-Type', 'text/plain') // Avoid pre-flight.
114-
xhr.send(data)
115-
setTimeout(() => {
116-
if (!handled) {
117-
xhr.abort()
112+
var blocked = false
113+
xhr.onerror = xhr.ontimeout = () => {
114+
if (xhr.status === 0) {
115+
blocked = true
116+
this.requestQueue.splice(0, this.requestQueue.length)
118117
}
119-
}, this.networkTimeoutSeconds * 1000)
118+
}
119+
if (!blocked) {
120+
xhr.open(method, url, true)
121+
xhr.setRequestHeader('Content-Type', 'text/plain') // Avoid pre-flight.
122+
xhr.send(data)
123+
setTimeout(() => {
124+
if (!handled) {
125+
xhr.abort()
126+
}
127+
}, this.networkTimeoutSeconds * 1000)
128+
}
120129
}
121130

122131
/**

test/mocks/external.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,12 @@ xhrMock.resolveRequest = function() {
3131
jest.runAllTimers()
3232
}
3333
}
34+
35+
xhrMock.blockRequest = function() {
36+
const xhr = xhrQueue.shift()
37+
if (xhr) {
38+
xhr.status = 0
39+
xhr.onerror()
40+
jest.runAllTimers()
41+
}
42+
}

test/specs/Network.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,24 @@ describe(Network, () => {
2222

2323
xhrMock.resolveRequest()
2424
xhrMock.resolveRequest()
25+
jest.runAllTimers()
2526

2627
expect(success).toHaveBeenCalledTimes(2)
2728
expect(error).toHaveBeenCalledTimes(0)
2829
})
30+
31+
it('stops sending requests if they are blocked', () => {
32+
jest.useFakeTimers()
33+
const success = jest.fn()
34+
const error = jest.fn()
35+
36+
network.ajax('POST', 'http://test.com/', {}, success, error, true, true)
37+
xhrMock.blockRequest()
38+
network.ajax('POST', 'http://test.com/', {}, success, error, true, true)
39+
40+
jest.runAllTimers()
41+
42+
expect(success).toHaveBeenCalledTimes(0)
43+
expect(error).toHaveBeenCalledTimes(0)
44+
})
2945
})

0 commit comments

Comments
 (0)