FetchUtilsTests.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. const { expect } = require('chai')
  2. const { FetchError, AbortError } = require('node-fetch')
  3. const { Readable } = require('stream')
  4. const { once } = require('events')
  5. const { TestServer } = require('./helpers/TestServer')
  6. const {
  7. fetchJson,
  8. fetchStream,
  9. fetchNothing,
  10. fetchRedirect,
  11. fetchString,
  12. RequestFailedError,
  13. } = require('../..')
  14. const PORT = 30001
  15. describe('fetch-utils', function () {
  16. before(async function () {
  17. this.server = new TestServer()
  18. await this.server.start(PORT)
  19. this.url = path => `http://127.0.0.1:${PORT}${path}`
  20. })
  21. after(async function () {
  22. await this.server.stop()
  23. })
  24. describe('fetchJson', function () {
  25. it('parses a JSON response', async function () {
  26. const json = await fetchJson(this.url('/json/hello'))
  27. expect(json).to.deep.equal({ msg: 'hello' })
  28. })
  29. it('parses JSON in the request', async function () {
  30. const json = await fetchJson(this.url('/json/add'), {
  31. method: 'POST',
  32. json: { a: 2, b: 3 },
  33. })
  34. expect(json).to.deep.equal({ sum: 5 })
  35. })
  36. it('accepts stringified JSON as body', async function () {
  37. const json = await fetchJson(this.url('/json/add'), {
  38. method: 'POST',
  39. body: JSON.stringify({ a: 2, b: 3 }),
  40. headers: { 'Content-Type': 'application/json' },
  41. })
  42. expect(json).to.deep.equal({ sum: 5 })
  43. })
  44. it('throws a FetchError when the payload is not JSON', async function () {
  45. await expect(fetchJson(this.url('/hello'))).to.be.rejectedWith(FetchError)
  46. })
  47. it('aborts the request if JSON parsing fails', async function () {
  48. await expect(fetchJson(this.url('/large'))).to.be.rejectedWith(FetchError)
  49. await expectRequestAborted(this.server.lastReq)
  50. })
  51. it('handles errors when the payload is JSON', async function () {
  52. await expect(fetchJson(this.url('/json/500'))).to.be.rejectedWith(
  53. RequestFailedError
  54. )
  55. await expectRequestAborted(this.server.lastReq)
  56. })
  57. it('handles errors when the payload is not JSON', async function () {
  58. await expect(fetchJson(this.url('/500'))).to.be.rejectedWith(
  59. RequestFailedError
  60. )
  61. await expectRequestAborted(this.server.lastReq)
  62. })
  63. it('supports abort signals', async function () {
  64. await expect(
  65. fetchJson(this.url('/hang'), { signal: AbortSignal.timeout(10) })
  66. ).to.be.rejectedWith(AbortError)
  67. await expectRequestAborted(this.server.lastReq)
  68. })
  69. it('supports basic auth', async function () {
  70. const json = await fetchJson(this.url('/json/basic-auth'), {
  71. basicAuth: { user: 'user', password: 'pass' },
  72. })
  73. expect(json).to.deep.equal({ key: 'verysecret' })
  74. })
  75. it("destroys the request body if it doesn't get consumed", async function () {
  76. const stream = Readable.from(infiniteIterator())
  77. await fetchJson(this.url('/json/ignore-request'), {
  78. method: 'POST',
  79. body: stream,
  80. })
  81. expect(stream.destroyed).to.be.true
  82. })
  83. })
  84. describe('fetchStream', function () {
  85. it('returns a stream', async function () {
  86. const stream = await fetchStream(this.url('/large'))
  87. const text = await streamToString(stream)
  88. expect(text).to.equal(this.server.largePayload)
  89. })
  90. it('aborts the request when the stream is destroyed', async function () {
  91. const stream = await fetchStream(this.url('/large'))
  92. stream.destroy()
  93. await expectRequestAborted(this.server.lastReq)
  94. })
  95. it('aborts the request when the request body is destroyed', async function () {
  96. const stream = Readable.from(infiniteIterator())
  97. const promise = fetchStream(this.url('/hang'), {
  98. method: 'POST',
  99. body: stream,
  100. })
  101. stream.destroy()
  102. await expect(promise).to.be.rejectedWith(AbortError)
  103. await expectRequestAborted(this.server.lastReq)
  104. })
  105. it('handles errors', async function () {
  106. await expect(fetchStream(this.url('/500'))).to.be.rejectedWith(
  107. RequestFailedError
  108. )
  109. await expectRequestAborted(this.server.lastReq)
  110. })
  111. it('supports abort signals', async function () {
  112. await expect(
  113. fetchStream(this.url('/hang'), { signal: AbortSignal.timeout(10) })
  114. ).to.be.rejectedWith(AbortError)
  115. await expectRequestAborted(this.server.lastReq)
  116. })
  117. it('destroys the request body when an error occurs', async function () {
  118. const stream = Readable.from(infiniteIterator())
  119. await expect(
  120. fetchStream(this.url('/hang'), {
  121. body: stream,
  122. signal: AbortSignal.timeout(10),
  123. })
  124. ).to.be.rejectedWith(AbortError)
  125. expect(stream.destroyed).to.be.true
  126. })
  127. })
  128. describe('fetchNothing', function () {
  129. it('closes the connection', async function () {
  130. await fetchNothing(this.url('/large'))
  131. await expectRequestAborted(this.server.lastReq)
  132. })
  133. it('aborts the request when the request body is destroyed', async function () {
  134. const stream = Readable.from(infiniteIterator())
  135. const promise = fetchNothing(this.url('/hang'), {
  136. method: 'POST',
  137. body: stream,
  138. })
  139. stream.destroy()
  140. await expect(promise).to.be.rejectedWith(AbortError)
  141. await expectRequestAborted(this.server.lastReq)
  142. })
  143. it("doesn't abort the request if the request body ends normally", async function () {
  144. const stream = Readable.from('hello there')
  145. await fetchNothing(this.url('/sink'), { method: 'POST', body: stream })
  146. })
  147. it('handles errors', async function () {
  148. await expect(fetchNothing(this.url('/500'))).to.be.rejectedWith(
  149. RequestFailedError
  150. )
  151. await expectRequestAborted(this.server.lastReq)
  152. })
  153. it('supports abort signals', async function () {
  154. await expect(
  155. fetchNothing(this.url('/hang'), { signal: AbortSignal.timeout(10) })
  156. ).to.be.rejectedWith(AbortError)
  157. await expectRequestAborted(this.server.lastReq)
  158. })
  159. it('destroys the request body when an error occurs', async function () {
  160. const stream = Readable.from(infiniteIterator())
  161. await expect(
  162. fetchNothing(this.url('/hang'), {
  163. body: stream,
  164. signal: AbortSignal.timeout(10),
  165. })
  166. ).to.be.rejectedWith(AbortError)
  167. expect(stream.destroyed).to.be.true
  168. })
  169. })
  170. describe('fetchString', function () {
  171. it('returns a string', async function () {
  172. const body = await fetchString(this.url('/hello'))
  173. expect(body).to.equal('hello')
  174. })
  175. it('handles errors', async function () {
  176. await expect(fetchString(this.url('/500'))).to.be.rejectedWith(
  177. RequestFailedError
  178. )
  179. await expectRequestAborted(this.server.lastReq)
  180. })
  181. })
  182. describe('fetchRedirect', function () {
  183. it('returns the immediate redirect', async function () {
  184. const body = await fetchRedirect(this.url('/redirect/1'))
  185. expect(body).to.equal(this.url('/redirect/2'))
  186. })
  187. it('rejects status 200', async function () {
  188. await expect(fetchRedirect(this.url('/hello'))).to.be.rejectedWith(
  189. RequestFailedError
  190. )
  191. await expectRequestAborted(this.server.lastReq)
  192. })
  193. it('rejects empty redirect', async function () {
  194. await expect(fetchRedirect(this.url('/redirect/empty-location')))
  195. .to.be.rejectedWith(RequestFailedError)
  196. .and.eventually.have.property('cause')
  197. .and.to.have.property('message')
  198. .to.equal('missing Location response header on 3xx response')
  199. await expectRequestAborted(this.server.lastReq)
  200. })
  201. it('handles errors', async function () {
  202. await expect(fetchRedirect(this.url('/500'))).to.be.rejectedWith(
  203. RequestFailedError
  204. )
  205. await expectRequestAborted(this.server.lastReq)
  206. })
  207. })
  208. })
  209. async function streamToString(stream) {
  210. let s = ''
  211. for await (const chunk of stream) {
  212. s += chunk
  213. }
  214. return s
  215. }
  216. async function* infiniteIterator() {
  217. let i = 1
  218. while (true) {
  219. yield `chunk ${i++}\n`
  220. }
  221. }
  222. async function expectRequestAborted(req) {
  223. if (!req.destroyed) {
  224. await once(req, 'close')
  225. expect(req.destroyed).to.be.true
  226. }
  227. }