No Description

test-fetch.js 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import RNTest from './react-native-testkit/'
  2. import React from 'react'
  3. import RNFetchBlob from 'react-native-fetch-blob'
  4. import {
  5. StyleSheet,
  6. Text,
  7. View,
  8. ScrollView,
  9. Platform,
  10. Dimensions,
  11. Image,
  12. } from 'react-native';
  13. window.Blob = RNFetchBlob.polyfill.Blob
  14. window.File = RNFetchBlob.polyfill.File
  15. window.fetch = new RNFetchBlob.polyfill.Fetch({
  16. auto : true,
  17. binaryContentTypes : ['image/', 'video/', 'audio/']
  18. }).build()
  19. const fs = RNFetchBlob.fs
  20. const { Assert, Comparer, Info, prop } = RNTest
  21. const describe = RNTest.config({
  22. group : 'Fetch polyfill',
  23. run : true,
  24. expand : true,
  25. timeout : 10000,
  26. })
  27. const { TEST_SERVER_URL, TEST_SERVER_URL_SSL, FILENAME, DROPBOX_TOKEN, styles } = prop()
  28. const dirs = RNFetchBlob.fs.dirs
  29. let prefix = ((Platform.OS === 'android') ? 'file://' : '')
  30. describe('GET request test : unicode text -> any', (report, done) => {
  31. function get(fn1, fn2) {
  32. return fetch(`${TEST_SERVER_URL}/unicode`, { method : 'GET'})
  33. .then((res) => fn1(res))
  34. .then((data) => fn2(data))
  35. }
  36. let promises =
  37. [
  38. get((res) => res.json(), (json) => {
  39. report(<Assert key="json data correct" expect={'你好!'} actual={json.data}/>)
  40. }),
  41. get((res) => res.text(), (text) => {
  42. report(<Assert key="text data correct" expect={'你好!'} actual={JSON.parse(text).data}/>)
  43. }),
  44. get((res) => res.blob(), (blob) => {
  45. return blob.readBlob('utf8').then((text) => {
  46. report(<Assert key="blob data correct" expect={'你好!'} actual={JSON.parse(text).data}/>)
  47. })
  48. }),
  49. // get((res) => res.arrayBuffer(), (text) => {
  50. // report(<Assert key="text data correct" expect={'你好!'} actual={JSON.parse(text).data}/>)
  51. // })
  52. ]
  53. Promise.all(promises).then(() => {
  54. done()
  55. })
  56. })
  57. describe('GET request test : path -> any', (report, done) => {
  58. function get(fn1, fn2, fn3) {
  59. fetch(`${TEST_SERVER_URL}/public/github.png`, { method : 'GET'})
  60. .then((res) => fn1(res))
  61. .then((data) => fn2(data))
  62. .catch((err) => fn3(err))
  63. }
  64. let contentLength = 0
  65. let isIOS = Platform.OS === 'ios'
  66. let promises = [
  67. // FIXME: IOS only
  68. // https://github.com/facebook/react-native/issues/9178
  69. get((res) => {
  70. if(isIOS)
  71. return res.json()
  72. return Promise.resolve()
  73. }, (data) => {
  74. report(<Assert key="should not convert blob to JSON (IOS only)" expect={true} actual={false} />)
  75. }, (err) => {
  76. report(<Assert key="should not convert blob to JSON (IOS only)" expect={true} actual={true} />)
  77. }),
  78. // FIXME: IOS only
  79. // https://github.com/facebook/react-native/issues/9178
  80. get((res) => {
  81. contentLength = res.headers['Content-Length']
  82. if(isIOS)
  83. return res.text()
  84. return Promise.resolve()
  85. }, (data) => {
  86. try {
  87. report(<Assert key="content length should correct (IOS only)" expect={Math.floor(contentLength)} actual={data ? data.length : 0} />)
  88. } catch(e){}
  89. }, (err) => {
  90. console.warn(err, err.stack)
  91. }),
  92. get((res) => {
  93. contentLength = res.headers['Content-Length']
  94. return res.blob()
  95. }, (blob) => {
  96. return fs.stat(blob._ref).then((stat) => {
  97. report(<Assert key="stored file size correct" expect={contentLength} actual={stat.size} />)
  98. return blob.readBlob('base64')
  99. })
  100. .then((b64) => {
  101. report(<Info key="stored image">
  102. <Image style={styles.image} source={{uri : 'data:image/png;BASE64 ,' + b64}}/>
  103. </Info>)
  104. })
  105. }, (err) => {
  106. console.warn(err, err.stack)
  107. })
  108. ]
  109. Promise.all(promises).then( () => done() )
  110. })
  111. describe('POST different kinds of body', (report, done) => {
  112. let image = RNTest.prop('image')
  113. let tmpPath = dirs.DocumentDir + '/tmp-' + Date.now()
  114. function upload(desc, pBody) {
  115. let name = `fetch-replacement-${Platform.OS}-${Date.now()}-${Math.random()}.png`
  116. return pBody.then((body) =>
  117. fetch('https://content.dropboxapi.com/2/files/upload', {
  118. method : 'post',
  119. headers : {
  120. Authorization : `Bearer ${DROPBOX_TOKEN}`,
  121. 'Dropbox-API-Arg': '{\"path\": \"/rn-upload/'+name+'\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}',
  122. 'Content-Type' : 'application/octet-stream'
  123. },
  124. body})
  125. )
  126. .then((res) => {
  127. return res.json()
  128. })
  129. .then((info) => {
  130. report(<Assert key={desc} expect={name} actual={info.name}/>)
  131. })
  132. }
  133. fetch(`${TEST_SERVER_URL}/public/github2.jpg`)
  134. .then((res) => res.blob())
  135. .then((b) => b.readBlob('base64'))
  136. .then((image) => {
  137. let tests = [
  138. upload('upload base64 encoded body', Promise.resolve(image)),
  139. upload('upload Blob body', Blob.build(image, 'image/png;BASE64')),
  140. upload('upload file path body', fs.writeFile(tmpPath, image, 'base64').then(() => {
  141. Promise.resolve(RNFetchBlob.wrap(tmpPath))
  142. }))
  143. ]
  144. Promise.all(tests).then(() => done())
  145. })
  146. })
  147. describe('Request header correctness', (report, done) => {
  148. let expect = {
  149. 'hello' : 'world',
  150. 'Content-Type' : 'application/json',
  151. 'foo' : encodeURIComponent('福' + Date.now())
  152. }
  153. fetch(`${TEST_SERVER_URL}/xhr-header`, {
  154. method : 'GET',
  155. headers : expect
  156. })
  157. .then((res) => res.json())
  158. .then((actual) => {
  159. report(<Info key={JSON.stringify(actual)}/>)
  160. report(<Assert key="header field test #1" expect={expect.hello} actual={actual.hello}/>)
  161. report(<Assert key="header field test #2" expect={expect['content-type']} actual={actual['content-type']}/>)
  162. report(<Assert key="header field test #3" expect={expect.foo} actual={actual.foo}/>)
  163. done()
  164. })
  165. })
  166. describe('Upload form data ', (report, done) => {
  167. let form = new FormData()
  168. let expectName = 'fetch-replacement-test' + new Date()
  169. File
  170. .build('test-image.png', RNTest.prop('image'), { type : 'image/png;BASE64' })
  171. .then((file) => {
  172. form.append('name', expectName)
  173. form.append('file', file)
  174. return fetch(`${TEST_SERVER_URL}/upload-form`, {
  175. method : 'POST',
  176. body : form
  177. })
  178. })
  179. .then((res) => res.json())
  180. .then((json) => {
  181. report(
  182. <Assert key="form data verify" expect={expectName} actual={json.fields.name}/>,
  183. <Assert key="file size verify" expect={23975} actual={json.files[0].size}/>,
  184. <Assert key="form data file name verify" expect={'test-image.png'} actual={json.files[0].originalname}/>
  185. )
  186. done()
  187. })
  188. })