Uppy.test.js 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070
  1. /* eslint no-console: "off", no-restricted-syntax: "off" */
  2. const fs = require('fs')
  3. const path = require('path')
  4. const prettierBytes = require('@transloadit/prettier-bytes')
  5. const Core = require('./index')
  6. const UIPlugin = require('./UIPlugin')
  7. const AcquirerPlugin1 = require('../../../../test/mocks/acquirerPlugin1')
  8. const AcquirerPlugin2 = require('../../../../test/mocks/acquirerPlugin2')
  9. const InvalidPlugin = require('../../../../test/mocks/invalidPlugin')
  10. const InvalidPluginWithoutId = require('../../../../test/mocks/invalidPluginWithoutId')
  11. const InvalidPluginWithoutType = require('../../../../test/mocks/invalidPluginWithoutType')
  12. const DeepFrozenStore = require('../../../../test/resources/DeepFrozenStore.js')
  13. jest.mock('nanoid/non-secure', () => {
  14. return { nanoid: () => 'cjd09qwxb000dlql4tp4doz8h' }
  15. })
  16. jest.mock('@uppy/utils/lib/findDOMElement', () => {
  17. return () => null
  18. })
  19. const sampleImage = fs.readFileSync(path.join(__dirname, '../../../../test/resources/image.jpg'))
  20. describe('src/Core', () => {
  21. const RealCreateObjectUrl = global.URL.createObjectURL
  22. beforeEach(() => {
  23. global.URL.createObjectURL = jest.fn().mockReturnValue('newUrl')
  24. })
  25. afterEach(() => {
  26. global.URL.createObjectURL = RealCreateObjectUrl
  27. })
  28. it('should expose a class', () => {
  29. const core = new Core()
  30. expect(core.constructor.name).toEqual('Uppy')
  31. })
  32. it('should have a string `id` option that defaults to "uppy"', () => {
  33. const core = new Core()
  34. expect(core.getID()).toEqual('uppy')
  35. const core2 = new Core({ id: 'profile' })
  36. expect(core2.getID()).toEqual('profile')
  37. })
  38. describe('plugins', () => {
  39. it('should add a plugin to the plugin stack', () => {
  40. const core = new Core()
  41. core.use(AcquirerPlugin1)
  42. expect(Object.keys(core[Symbol.for('uppy test: getPlugins')]('acquirer')).length).toEqual(1)
  43. })
  44. it('should prevent the same plugin from being added more than once', () => {
  45. const core = new Core()
  46. core.use(AcquirerPlugin1)
  47. expect(() => {
  48. core.use(AcquirerPlugin1)
  49. }).toThrowErrorMatchingSnapshot()
  50. })
  51. it('should not be able to add an invalid plugin', () => {
  52. const core = new Core()
  53. expect(() => {
  54. core.use(InvalidPlugin)
  55. }).toThrowErrorMatchingSnapshot()
  56. })
  57. it('should not be able to add a plugin that has no id', () => {
  58. const core = new Core()
  59. expect(() => core.use(InvalidPluginWithoutId)).toThrowErrorMatchingSnapshot()
  60. })
  61. it('should not be able to add a plugin that has no type', () => {
  62. const core = new Core()
  63. expect(() => core.use(InvalidPluginWithoutType)).toThrowErrorMatchingSnapshot()
  64. })
  65. it('should return the plugin that matches the specified name', () => {
  66. const core = new Core()
  67. expect(core.getPlugin('foo')).toEqual(undefined)
  68. core.use(AcquirerPlugin1)
  69. const plugin = core.getPlugin('TestSelector1')
  70. expect(plugin.id).toEqual('TestSelector1')
  71. expect(plugin instanceof UIPlugin)
  72. })
  73. it('should call the specified method on all the plugins', () => {
  74. const core = new Core()
  75. core.use(AcquirerPlugin1)
  76. core.use(AcquirerPlugin2)
  77. core.iteratePlugins(plugin => {
  78. plugin.run('hello')
  79. })
  80. expect(core[Symbol.for('uppy test: getPlugins')]('acquirer')[0].mocks.run.mock.calls.length).toEqual(1)
  81. expect(core[Symbol.for('uppy test: getPlugins')]('acquirer')[0].mocks.run.mock.calls[0]).toEqual([
  82. 'hello',
  83. ])
  84. expect(core[Symbol.for('uppy test: getPlugins')]('acquirer')[1].mocks.run.mock.calls.length).toEqual(1)
  85. expect(core[Symbol.for('uppy test: getPlugins')]('acquirer')[1].mocks.run.mock.calls[0]).toEqual([
  86. 'hello',
  87. ])
  88. })
  89. it('should uninstall and the remove the specified plugin', () => {
  90. const core = new Core()
  91. core.use(AcquirerPlugin1)
  92. core.use(AcquirerPlugin2)
  93. expect(Object.keys(core[Symbol.for('uppy test: getPlugins')]('acquirer')).length).toEqual(2)
  94. const plugin = core.getPlugin('TestSelector1')
  95. core.removePlugin(plugin)
  96. expect(Object.keys(core[Symbol.for('uppy test: getPlugins')]('acquirer')).length).toEqual(1)
  97. expect(plugin.mocks.uninstall.mock.calls.length).toEqual(1)
  98. expect(core[Symbol.for('uppy test: getPlugins')]('acquirer')[0].mocks.run.mock.calls.length).toEqual(0)
  99. })
  100. })
  101. describe('state', () => {
  102. it('should update all the plugins with the new state when the updateAll method is called', () => {
  103. const core = new Core()
  104. core.use(AcquirerPlugin1)
  105. core.use(AcquirerPlugin2)
  106. core.updateAll({ foo: 'bar' })
  107. expect(core[Symbol.for('uppy test: getPlugins')]('acquirer')[0].mocks.update.mock.calls.length).toEqual(1)
  108. expect(core[Symbol.for('uppy test: getPlugins')]('acquirer')[0].mocks.update.mock.calls[0]).toEqual([
  109. { foo: 'bar' },
  110. ])
  111. expect(core[Symbol.for('uppy test: getPlugins')]('acquirer')[1].mocks.update.mock.calls.length).toEqual(1)
  112. expect(core[Symbol.for('uppy test: getPlugins')]('acquirer')[1].mocks.update.mock.calls[0]).toEqual([
  113. { foo: 'bar' },
  114. ])
  115. })
  116. it('should update the state', () => {
  117. const core = new Core()
  118. const stateUpdateEventMock = jest.fn()
  119. core.on('state-update', stateUpdateEventMock)
  120. core.use(AcquirerPlugin1)
  121. core.use(AcquirerPlugin2)
  122. core.setState({ foo: 'bar', bee: 'boo' })
  123. core.setState({ foo: 'baar' })
  124. const newState = {
  125. bee: 'boo',
  126. capabilities: { individualCancellation: true, uploadProgress: true, resumableUploads: false },
  127. files: {},
  128. currentUploads: {},
  129. allowNewUpload: true,
  130. foo: 'baar',
  131. info: [],
  132. meta: {},
  133. plugins: {},
  134. totalProgress: 0,
  135. recoveredState: null,
  136. }
  137. expect(core.getState()).toEqual(newState)
  138. expect(core[Symbol.for('uppy test: getPlugins')]('acquirer')[0].mocks.update.mock.calls[1]).toEqual([
  139. newState,
  140. ])
  141. expect(core[Symbol.for('uppy test: getPlugins')]('acquirer')[1].mocks.update.mock.calls[1]).toEqual([
  142. newState,
  143. ])
  144. expect(stateUpdateEventMock.mock.calls.length).toEqual(2)
  145. // current state
  146. expect(stateUpdateEventMock.mock.calls[1][0]).toEqual({
  147. bee: 'boo',
  148. capabilities: { individualCancellation: true, uploadProgress: true, resumableUploads: false },
  149. files: {},
  150. currentUploads: {},
  151. allowNewUpload: true,
  152. foo: 'bar',
  153. info: [],
  154. meta: {},
  155. plugins: {},
  156. totalProgress: 0,
  157. recoveredState: null,
  158. })
  159. // new state
  160. expect(stateUpdateEventMock.mock.calls[1][1]).toEqual({
  161. bee: 'boo',
  162. capabilities: { individualCancellation: true, uploadProgress: true, resumableUploads: false },
  163. files: {},
  164. currentUploads: {},
  165. allowNewUpload: true,
  166. foo: 'baar',
  167. info: [],
  168. meta: {},
  169. plugins: {},
  170. totalProgress: 0,
  171. recoveredState: null,
  172. })
  173. })
  174. it('should get the state', () => {
  175. const core = new Core()
  176. core.setState({ foo: 'bar' })
  177. expect(core.getState()).toMatchObject({ foo: 'bar' })
  178. })
  179. })
  180. it('should reset when the reset method is called', () => {
  181. // use DeepFrozenStore in some tests to make sure we are not mutating things
  182. const core = new Core({
  183. store: DeepFrozenStore(),
  184. })
  185. // const corePauseEventMock = jest.fn()
  186. const coreCancelEventMock = jest.fn()
  187. const coreStateUpdateEventMock = jest.fn()
  188. core.on('cancel-all', coreCancelEventMock)
  189. core.on('state-update', coreStateUpdateEventMock)
  190. core.setState({ foo: 'bar', totalProgress: 30 })
  191. core.reset()
  192. expect(coreCancelEventMock.mock.calls.length).toEqual(1)
  193. expect(coreStateUpdateEventMock.mock.calls.length).toEqual(2)
  194. expect(coreStateUpdateEventMock.mock.calls[1][1]).toEqual({
  195. capabilities: { individualCancellation: true, uploadProgress: true, resumableUploads: false },
  196. files: {},
  197. currentUploads: {},
  198. allowNewUpload: true,
  199. error: null,
  200. foo: 'bar',
  201. info: [],
  202. meta: {},
  203. plugins: {},
  204. totalProgress: 0,
  205. recoveredState: null,
  206. })
  207. })
  208. it('should clear all uploads and files on cancelAll()', () => {
  209. const core = new Core()
  210. core.addFile({
  211. source: 'jest',
  212. name: 'foo1.jpg',
  213. type: 'image/jpeg',
  214. data: new File([sampleImage], { type: 'image/jpeg' }),
  215. })
  216. core.addFile({
  217. source: 'jest',
  218. name: 'foo2.jpg',
  219. type: 'image/jpeg',
  220. data: new File([sampleImage], { type: 'image/jpeg' }),
  221. })
  222. const fileIDs = Object.keys(core.getState().files)
  223. const id = core[Symbol.for('uppy test: createUpload')](fileIDs)
  224. expect(core.getState().currentUploads[id]).toBeDefined()
  225. expect(Object.keys(core.getState().files).length).toEqual(2)
  226. core.cancelAll()
  227. expect(core.getState().currentUploads[id]).toBeUndefined()
  228. expect(Object.keys(core.getState().files).length).toEqual(0)
  229. })
  230. it('should close, reset and uninstall when the close method is called', () => {
  231. // use DeepFrozenStore in some tests to make sure we are not mutating things
  232. const core = new Core({
  233. store: DeepFrozenStore(),
  234. })
  235. core.use(AcquirerPlugin1)
  236. const coreCancelEventMock = jest.fn()
  237. const coreStateUpdateEventMock = jest.fn()
  238. const plugin = core[Symbol.for('uppy test: getPlugins')]('acquirer')[0]
  239. core.on('cancel-all', coreCancelEventMock)
  240. core.on('state-update', coreStateUpdateEventMock)
  241. core.close()
  242. expect(coreCancelEventMock.mock.calls.length).toEqual(1)
  243. expect(coreStateUpdateEventMock.mock.calls.length).toEqual(1)
  244. expect(coreStateUpdateEventMock.mock.calls[0][1]).toEqual({
  245. capabilities: { individualCancellation: true, uploadProgress: true, resumableUploads: false },
  246. files: {},
  247. currentUploads: {},
  248. allowNewUpload: true,
  249. error: null,
  250. info: [],
  251. meta: {},
  252. plugins: {},
  253. totalProgress: 0,
  254. recoveredState: null,
  255. })
  256. expect(plugin.mocks.uninstall.mock.calls.length).toEqual(1)
  257. const pluginIteration = jest.fn()
  258. core.iteratePlugins(pluginIteration)
  259. expect(pluginIteration.mock.calls.length).toEqual(0)
  260. })
  261. describe('upload hooks', () => {
  262. it('should add data returned from upload hooks to the .upload() result', () => {
  263. const core = new Core()
  264. core.addPreProcessor((_, uploadID) => {
  265. core.addResultData(uploadID, { pre: 'ok' })
  266. })
  267. core.addPostProcessor((_, uploadID) => {
  268. core.addResultData(uploadID, { post: 'ok' })
  269. })
  270. core.addUploader((_, uploadID) => {
  271. core.addResultData(uploadID, { upload: 'ok' })
  272. })
  273. return core.upload().then((result) => {
  274. expect(result.pre).toBe('ok')
  275. expect(result.upload).toBe('ok')
  276. expect(result.post).toBe('ok')
  277. })
  278. })
  279. })
  280. describe('preprocessors', () => {
  281. it('should add and remove preprocessor', () => {
  282. const core = new Core()
  283. const preprocessor = () => { }
  284. expect(core.removePreProcessor(preprocessor)).toBe(false)
  285. core.addPreProcessor(preprocessor)
  286. expect(core.removePreProcessor(preprocessor)).toBe(true)
  287. expect(core.removePreProcessor(preprocessor)).toBe(false)
  288. })
  289. it('should execute all the preprocessors when uploading a file', () => {
  290. const core = new Core()
  291. const preprocessor1 = jest.fn()
  292. const preprocessor2 = jest.fn()
  293. core.addPreProcessor(preprocessor1)
  294. core.addPreProcessor(preprocessor2)
  295. core.addFile({
  296. source: 'jest',
  297. name: 'foo.jpg',
  298. type: 'image/jpeg',
  299. data: new File([sampleImage], { type: 'image/jpeg' }),
  300. })
  301. return core.upload()
  302. .then(() => {
  303. const fileId = Object.keys(core.getState().files)[0]
  304. expect(preprocessor1.mock.calls.length).toEqual(1)
  305. expect(preprocessor1.mock.calls[0][0].length).toEqual(1)
  306. expect(preprocessor1.mock.calls[0][0][0]).toEqual(fileId)
  307. expect(preprocessor2.mock.calls[0][0].length).toEqual(1)
  308. expect(preprocessor2.mock.calls[0][0][0]).toEqual(fileId)
  309. })
  310. })
  311. it('should not pass removed file IDs to next step', async () => {
  312. const core = new Core()
  313. const uploader = jest.fn()
  314. core.addPreProcessor((fileIDs) => {
  315. core.removeFile(fileIDs[0])
  316. })
  317. core.addUploader(uploader)
  318. core.addFile({
  319. source: 'jest',
  320. name: 'rmd.jpg',
  321. type: 'image/jpeg',
  322. data: new File([sampleImage], { type: 'image/jpeg' }),
  323. })
  324. core.addFile({
  325. source: 'jest',
  326. name: 'kept.jpg',
  327. type: 'image/jpeg',
  328. data: new File([sampleImage], { type: 'image/jpeg' }),
  329. })
  330. await core.upload()
  331. expect(uploader.mock.calls.length).toEqual(1)
  332. expect(uploader.mock.calls[0][0].length).toEqual(1, 'Got 1 file ID')
  333. expect(core.getFile(uploader.mock.calls[0][0][0]).name).toEqual('kept.jpg')
  334. })
  335. it('should update the file progress state when preprocess-progress event is fired', () => {
  336. const core = new Core()
  337. core.addFile({
  338. source: 'jest',
  339. name: 'foo.jpg',
  340. type: 'image/jpeg',
  341. data: new File([sampleImage], { type: 'image/jpeg' }),
  342. })
  343. const fileId = Object.keys(core.getState().files)[0]
  344. const file = core.getFile(fileId)
  345. core.emit('preprocess-progress', file, {
  346. mode: 'determinate',
  347. message: 'something',
  348. value: 0,
  349. })
  350. expect(core.getFile(fileId).progress).toEqual({
  351. percentage: 0,
  352. bytesUploaded: 0,
  353. bytesTotal: 17175,
  354. uploadComplete: false,
  355. uploadStarted: null,
  356. preprocess: { mode: 'determinate', message: 'something', value: 0 },
  357. })
  358. })
  359. it('should update the file progress state when preprocess-complete event is fired', () => {
  360. const core = new Core()
  361. core.addFile({
  362. source: 'jest',
  363. name: 'foo.jpg',
  364. type: 'image/jpeg',
  365. data: new File([sampleImage], { type: 'image/jpeg' }),
  366. })
  367. const fileID = Object.keys(core.getState().files)[0]
  368. const file = core.getFile(fileID)
  369. core.emit('preprocess-complete', file, {
  370. mode: 'determinate',
  371. message: 'something',
  372. value: 0,
  373. })
  374. expect(core.getFile(fileID).progress).toEqual({
  375. percentage: 0,
  376. bytesUploaded: 0,
  377. bytesTotal: 17175,
  378. uploadComplete: false,
  379. uploadStarted: null,
  380. })
  381. })
  382. })
  383. describe('postprocessors', () => {
  384. it('should add and remove postprocessor', () => {
  385. const core = new Core()
  386. const postprocessor = () => { }
  387. expect(core.removePostProcessor(postprocessor)).toBe(false)
  388. core.addPostProcessor(postprocessor)
  389. expect(core.removePostProcessor(postprocessor)).toBe(true)
  390. expect(core.removePostProcessor(postprocessor)).toBe(false)
  391. })
  392. it('should execute all the postprocessors when uploading a file', () => {
  393. const core = new Core()
  394. const postprocessor1 = jest.fn()
  395. const postprocessor2 = jest.fn()
  396. core.addPostProcessor(postprocessor1)
  397. core.addPostProcessor(postprocessor2)
  398. core.addFile({
  399. source: 'jest',
  400. name: 'foo.jpg',
  401. type: 'image/jpeg',
  402. data: new File([sampleImage], { type: 'image/jpeg' }),
  403. })
  404. return core.upload().then(() => {
  405. expect(postprocessor1.mock.calls.length).toEqual(1)
  406. // const lastModifiedTime = new Date()
  407. // const fileId = 'foojpg' + lastModifiedTime.getTime()
  408. const fileId = 'uppy-foo/jpg-1e-image'
  409. expect(postprocessor1.mock.calls[0][0].length).toEqual(1)
  410. expect(postprocessor1.mock.calls[0][0][0].substring(0, 17)).toEqual(
  411. fileId.substring(0, 17),
  412. )
  413. expect(postprocessor2.mock.calls[0][0].length).toEqual(1)
  414. expect(postprocessor2.mock.calls[0][0][0].substring(0, 17)).toEqual(
  415. fileId.substring(0, 17),
  416. )
  417. })
  418. })
  419. it('should update the file progress state when postprocess-progress event is fired', () => {
  420. const core = new Core()
  421. core.addFile({
  422. source: 'jest',
  423. name: 'foo.jpg',
  424. type: 'image/jpeg',
  425. data: new File([sampleImage], { type: 'image/jpeg' }),
  426. })
  427. const fileId = Object.keys(core.getState().files)[0]
  428. const file = core.getFile(fileId)
  429. core.emit('postprocess-progress', file, {
  430. mode: 'determinate',
  431. message: 'something',
  432. value: 0,
  433. })
  434. expect(core.getFile(fileId).progress).toEqual({
  435. percentage: 0,
  436. bytesUploaded: 0,
  437. bytesTotal: 17175,
  438. uploadComplete: false,
  439. uploadStarted: null,
  440. postprocess: { mode: 'determinate', message: 'something', value: 0 },
  441. })
  442. })
  443. it('should update the file progress state when postprocess-complete event is fired', () => {
  444. const core = new Core()
  445. core.addFile({
  446. source: 'jest',
  447. name: 'foo.jpg',
  448. type: 'image/jpeg',
  449. data: new File([sampleImage], { type: 'image/jpeg' }),
  450. })
  451. const fileId = Object.keys(core.getState().files)[0]
  452. const file = core.getFile(fileId)
  453. core.emit('postprocess-complete', file, {
  454. mode: 'determinate',
  455. message: 'something',
  456. value: 0,
  457. })
  458. expect(core.getFile(fileId).progress).toEqual({
  459. percentage: 0,
  460. bytesUploaded: 0,
  461. bytesTotal: 17175,
  462. uploadComplete: false,
  463. uploadStarted: null,
  464. })
  465. })
  466. it('should report an error if post-processing a file fails', () => {
  467. const core = new Core()
  468. core.addFile({
  469. source: 'jest',
  470. name: 'foo.jpg',
  471. type: 'image/jpeg',
  472. data: new File([sampleImage], { type: 'image/jpeg' }),
  473. })
  474. const fileId = Object.keys(core.getState().files)[0]
  475. const file = core.getFile(fileId)
  476. core.emit('error', new Error('foooooo'), file)
  477. expect(core.getState().error).toEqual('foooooo')
  478. expect(core.upload()).resolves.toMatchObject({
  479. failed: [
  480. { name: 'foo.jpg' },
  481. ],
  482. })
  483. })
  484. })
  485. describe('uploaders', () => {
  486. it('should add and remove uploader', () => {
  487. const core = new Core()
  488. const uploader = () => { }
  489. expect(core.removeUploader(uploader)).toBe(false)
  490. core.addUploader(uploader)
  491. expect(core.removeUploader(uploader)).toBe(true)
  492. expect(core.removeUploader(uploader)).toBe(false)
  493. })
  494. })
  495. describe('adding a file', () => {
  496. it('should call onBeforeFileAdded if it was specified in the options when initialising the class', () => {
  497. const onBeforeFileAdded = jest.fn()
  498. const core = new Core({
  499. onBeforeFileAdded,
  500. })
  501. core.addFile({
  502. source: 'jest',
  503. name: 'foo.jpg',
  504. type: 'image/jpeg',
  505. data: new File([sampleImage], { type: 'image/jpeg' }),
  506. })
  507. expect(onBeforeFileAdded.mock.calls.length).toEqual(1)
  508. expect(onBeforeFileAdded.mock.calls[0][0].name).toEqual('foo.jpg')
  509. expect(onBeforeFileAdded.mock.calls[0][1]).toEqual({})
  510. })
  511. it('should add a file', () => {
  512. const fileData = new File([sampleImage], { type: 'image/jpeg' })
  513. const fileAddedEventMock = jest.fn()
  514. const core = new Core()
  515. core.on('file-added', fileAddedEventMock)
  516. const fileId = core.addFile({
  517. source: 'jest',
  518. name: 'foo.jpg',
  519. type: 'image/jpeg',
  520. data: fileData,
  521. })
  522. const newFile = {
  523. extension: 'jpg',
  524. id: fileId,
  525. isRemote: false,
  526. meta: { name: 'foo.jpg', type: 'image/jpeg' },
  527. name: 'foo.jpg',
  528. preview: undefined,
  529. data: fileData,
  530. progress: {
  531. bytesTotal: 17175,
  532. bytesUploaded: 0,
  533. percentage: 0,
  534. uploadComplete: false,
  535. uploadStarted: null,
  536. },
  537. remote: '',
  538. size: 17175,
  539. source: 'jest',
  540. type: 'image/jpeg',
  541. }
  542. expect(core.getFile(fileId)).toEqual(newFile)
  543. expect(fileAddedEventMock.mock.calls[0][0]).toEqual(newFile)
  544. })
  545. it('should not allow a file that does not meet the restrictions', () => {
  546. const core = new Core({
  547. restrictions: {
  548. allowedFileTypes: ['image/gif', 'video/webm'],
  549. },
  550. })
  551. expect(() => {
  552. core.addFile({
  553. source: 'jest',
  554. name: 'foo.jpg',
  555. type: 'image/jpeg',
  556. data: new File([sampleImage], { type: 'image/jpeg' }),
  557. })
  558. }).toThrow('You can only upload: image/gif, video/webm')
  559. expect(() => {
  560. core.addFile({
  561. source: 'jest',
  562. name: 'foo.webm',
  563. type: 'video/webm; codecs="vp8, opus"',
  564. data: new File([sampleImage], { type: 'video/webm; codecs="vp8, opus"' }),
  565. })
  566. }).not.toThrow()
  567. })
  568. it('should not allow a dupicate file, a file with the same id', () => {
  569. const core = new Core()
  570. const sameFileBlob = new File([sampleImage], { type: 'image/jpeg' })
  571. core.addFile({
  572. source: 'jest',
  573. name: 'foo.jpg',
  574. type: 'image/jpeg',
  575. data: sameFileBlob,
  576. })
  577. expect(() => {
  578. core.addFile({
  579. source: 'jest',
  580. name: 'foo.jpg',
  581. type: 'image/jpeg',
  582. data: sameFileBlob,
  583. meta: {
  584. notARelativePath: 'folder/a',
  585. },
  586. })
  587. }).toThrow(
  588. "Cannot add the duplicate file 'foo.jpg', it already exists",
  589. )
  590. expect(core.getFiles().length).toEqual(1)
  591. })
  592. it('should allow a duplicate file if its relativePath is different, thus the id is different', () => {
  593. const core = new Core()
  594. core.addFile({
  595. source: 'jest',
  596. name: 'foo.jpg',
  597. type: 'image/jpeg',
  598. data: new File([sampleImage], { type: 'image/jpeg' }),
  599. })
  600. core.addFile({
  601. source: 'jest',
  602. name: 'foo.jpg',
  603. type: 'image/jpeg',
  604. data: new File([sampleImage], { type: 'image/jpeg' }),
  605. meta: {
  606. relativePath: 'folder/a',
  607. },
  608. })
  609. expect(core.getFiles().length).toEqual(2)
  610. })
  611. it('should not allow a file if onBeforeFileAdded returned false', () => {
  612. const core = new Core({
  613. onBeforeFileAdded: (file) => {
  614. if (file.source === 'jest') {
  615. return false
  616. }
  617. return undefined
  618. },
  619. })
  620. expect(() => {
  621. core.addFile({
  622. source: 'jest',
  623. name: 'foo.jpg',
  624. type: 'image/jpeg',
  625. data: new File([sampleImage], { type: 'image/jpeg' }),
  626. })
  627. }).toThrow(
  628. 'Cannot add the file because onBeforeFileAdded returned false.',
  629. )
  630. expect(core.getFiles().length).toEqual(0)
  631. })
  632. describe('with allowMultipleUploadBatches: false', () => {
  633. it('allows no new files after upload', async () => {
  634. const core = new Core({ allowMultipleUploadBatches: false })
  635. core.addFile({
  636. source: 'jest',
  637. name: 'foo.jpg',
  638. type: 'image/jpeg',
  639. data: new File([sampleImage], { type: 'image/jpeg' }),
  640. })
  641. await core.upload()
  642. expect(() => {
  643. core.addFile({
  644. source: 'jest',
  645. name: '123.foo',
  646. type: 'image/jpeg',
  647. data: new File([sampleImage], { type: 'image/jpeg' }),
  648. })
  649. }).toThrow(
  650. /Cannot add more files/,
  651. )
  652. })
  653. it('allows no new files after upload with legacy allowMultipleUploads option', async () => {
  654. const core = new Core({ allowMultipleUploads: false })
  655. core.addFile({
  656. source: 'jest',
  657. name: 'foo.jpg',
  658. type: 'image/jpeg',
  659. data: new File([sampleImage], { type: 'image/jpeg' }),
  660. })
  661. await core.upload()
  662. expect(() => {
  663. core.addFile({
  664. source: 'jest',
  665. name: '123.foo',
  666. type: 'image/jpeg',
  667. data: new File([sampleImage], { type: 'image/jpeg' }),
  668. })
  669. }).toThrow(
  670. /Cannot add more files/,
  671. )
  672. })
  673. it('does not allow new files after the removeFile() if some file is still present', async () => {
  674. const core = new Core({ allowMultipleUploadBatches: false })
  675. // adding 2 files
  676. const fileId1 = core.addFile({
  677. source: 'jest',
  678. name: '1.jpg',
  679. type: 'image/jpeg',
  680. data: new File([sampleImage], { type: 'image/jpeg' }),
  681. })
  682. core.addFile({
  683. source: 'jest',
  684. name: '2.jpg',
  685. type: 'image/jpeg',
  686. data: new File([sampleImage], { type: 'image/jpeg' }),
  687. })
  688. // removing 1 file
  689. core.removeFile(fileId1)
  690. await expect(core.upload()).resolves.toBeDefined()
  691. })
  692. it('allows new files after the last removeFile()', async () => {
  693. const core = new Core({ allowMultipleUploadBatches: false })
  694. // adding 2 files
  695. const fileId1 = core.addFile({
  696. source: 'jest',
  697. name: '1.jpg',
  698. type: 'image/jpeg',
  699. data: new File([sampleImage], { type: 'image/jpeg' }),
  700. })
  701. const fileId2 = core.addFile({
  702. source: 'jest',
  703. name: '2.jpg',
  704. type: 'image/jpeg',
  705. data: new File([sampleImage], { type: 'image/jpeg' }),
  706. })
  707. // removing 2 files
  708. core.removeFile(fileId1)
  709. core.removeFile(fileId2)
  710. await expect(core.upload()).resolves.toBeDefined()
  711. })
  712. })
  713. it('does not dedupe different files', async () => {
  714. const core = new Core()
  715. const data = new Blob([sampleImage], { type: 'image/jpeg' })
  716. data.lastModified = 1562770350937
  717. core.addFile({
  718. source: 'jest',
  719. name: 'foo.jpg',
  720. type: 'image/jpeg',
  721. data,
  722. })
  723. core.addFile({
  724. source: 'jest',
  725. name: 'foo푸.jpg',
  726. type: 'image/jpeg',
  727. data,
  728. })
  729. expect(core.getFiles()).toHaveLength(2)
  730. expect(core.getFile('uppy-foo/jpg-1e-image/jpeg-17175-1562770350937')).toBeDefined()
  731. expect(core.getFile('uppy-foo//jpg-1l3o-1e-image/jpeg-17175-1562770350937')).toBeDefined()
  732. })
  733. })
  734. describe('uploading a file', () => {
  735. it('should return a { successful, failed } pair containing file objects', () => {
  736. const core = new Core()
  737. core.addUploader(() => Promise.resolve())
  738. core.addFile({ source: 'jest', name: 'foo.jpg', type: 'image/jpeg', data: new Uint8Array() })
  739. core.addFile({ source: 'jest', name: 'bar.jpg', type: 'image/jpeg', data: new Uint8Array() })
  740. return expect(core.upload()).resolves.toMatchObject({
  741. successful: [
  742. { name: 'foo.jpg' },
  743. { name: 'bar.jpg' },
  744. ],
  745. failed: [],
  746. })
  747. })
  748. it('should return files with errors in the { failed } key', () => {
  749. // use DeepFrozenStore in some tests to make sure we are not mutating things
  750. const core = new Core({
  751. store: DeepFrozenStore(),
  752. })
  753. core.addUploader((fileIDs) => {
  754. fileIDs.forEach((fileID) => {
  755. const file = core.getFile(fileID)
  756. if (/bar/.test(file.name)) {
  757. core.emit('upload-error', file, new Error('This is bar and I do not like bar'))
  758. }
  759. })
  760. return Promise.resolve()
  761. })
  762. core.addFile({ source: 'jest', name: 'foo.jpg', type: 'image/jpeg', data: new Uint8Array() })
  763. core.addFile({ source: 'jest', name: 'bar.jpg', type: 'image/jpeg', data: new Uint8Array() })
  764. return expect(core.upload()).resolves.toMatchObject({
  765. successful: [
  766. { name: 'foo.jpg' },
  767. ],
  768. failed: [
  769. { name: 'bar.jpg', error: 'This is bar and I do not like bar' },
  770. ],
  771. })
  772. })
  773. it('should only upload files that are not already assigned to another upload id', () => {
  774. const core = new Core()
  775. core.store.state.currentUploads = {
  776. upload1: {
  777. fileIDs: ['uppy-file1/jpg-1e-image/jpeg', 'uppy-file2/jpg-1e-image/jpeg', 'uppy-file3/jpg-1e-image/jpeg'],
  778. },
  779. upload2: {
  780. fileIDs: ['uppy-file4/jpg-1e-image/jpeg', 'uppy-file5/jpg-1e-image/jpeg', 'uppy-file6/jpg-1e-image/jpeg'],
  781. },
  782. }
  783. core.addUploader(() => Promise.resolve())
  784. core.addFile({ source: 'jest', name: 'foo.jpg', type: 'image/jpeg', data: new Uint8Array() })
  785. core.addFile({ source: 'jest', name: 'bar.jpg', type: 'image/jpeg', data: new Uint8Array() })
  786. core.addFile({ source: 'file3', name: 'file3.jpg', type: 'image/jpeg', data: new Uint8Array() })
  787. return expect(core.upload()).resolves.toMatchSnapshot()
  788. })
  789. it('should not upload if onBeforeUpload returned false', () => {
  790. const core = new Core({
  791. onBeforeUpload: (files) => {
  792. for (const fileId in files) {
  793. if (files[fileId].name === '123.foo') {
  794. return false
  795. }
  796. }
  797. return undefined
  798. },
  799. })
  800. core.addFile({
  801. source: 'jest',
  802. name: 'foo.jpg',
  803. type: 'image/jpeg',
  804. data: new File([sampleImage], { type: 'image/jpeg' }),
  805. })
  806. core.addFile({
  807. source: 'jest',
  808. name: 'bar.jpg',
  809. type: 'image/jpeg',
  810. data: new File([sampleImage], { type: 'image/jpeg' }),
  811. })
  812. core.addFile({
  813. source: 'jest',
  814. name: '123.foo',
  815. type: 'image/jpeg',
  816. data: new File([sampleImage], { type: 'image/jpeg' }),
  817. })
  818. return core.upload().catch((err) => {
  819. expect(err).toMatchObject(new Error('Not starting the upload because onBeforeUpload returned false'))
  820. })
  821. })
  822. it('only allows a single upload() batch when allowMultipleUploadBatches: false', async () => {
  823. const core = new Core({ allowMultipleUploadBatches: false })
  824. core.addFile({
  825. source: 'jest',
  826. name: 'foo.jpg',
  827. type: 'image/jpeg',
  828. data: new File([sampleImage], { type: 'image/jpeg' }),
  829. })
  830. core.addFile({
  831. source: 'jest',
  832. name: 'bar.jpg',
  833. type: 'image/jpeg',
  834. data: new File([sampleImage], { type: 'image/jpeg' }),
  835. })
  836. await expect(core.upload()).resolves.toBeDefined()
  837. await expect(core.upload()).rejects.toThrow(
  838. /Cannot create a new upload: already uploading\./,
  839. )
  840. })
  841. it('allows new files again with allowMultipleUploadBatches: false after reset() was called', async () => {
  842. const core = new Core({ allowMultipleUploadBatches: false })
  843. core.addFile({
  844. source: 'jest',
  845. name: 'bar.jpg',
  846. type: 'image/jpeg',
  847. data: new File([sampleImage], { type: 'image/jpeg' }),
  848. })
  849. await expect(core.upload()).resolves.toBeDefined()
  850. core.reset()
  851. core.addFile({
  852. source: 'jest',
  853. name: '123.foo',
  854. type: 'image/jpeg',
  855. data: new File([sampleImage], { type: 'image/jpeg' }),
  856. })
  857. await expect(core.upload()).resolves.toBeDefined()
  858. })
  859. })
  860. describe('removing a file', () => {
  861. it('should remove the file', () => {
  862. const fileRemovedEventMock = jest.fn()
  863. const core = new Core()
  864. core.on('file-removed', fileRemovedEventMock)
  865. core.addFile({
  866. source: 'jest',
  867. name: 'foo.jpg',
  868. type: 'image/jpeg',
  869. data: new File([sampleImage], { type: 'image/jpeg' }),
  870. })
  871. const fileId = Object.keys(core.getState().files)[0]
  872. expect(core.getFiles().length).toEqual(1)
  873. core.setState({
  874. totalProgress: 50,
  875. })
  876. const file = core.getFile(fileId)
  877. core.removeFile(fileId)
  878. expect(core.getFiles().length).toEqual(0)
  879. expect(fileRemovedEventMock.mock.calls[0][0]).toEqual(file)
  880. expect(core.getState().totalProgress).toEqual(0)
  881. })
  882. })
  883. describe('retries', () => {
  884. it('should start a new upload with failed files', async () => {
  885. const onUpload = jest.fn()
  886. const onRetryAll = jest.fn()
  887. const core = new Core()
  888. core.on('upload', onUpload)
  889. core.on('retry-all', onRetryAll)
  890. const id = core.addFile({
  891. source: 'jest',
  892. name: 'foo.jpg',
  893. type: 'image/jpeg',
  894. data: new File([sampleImage], { type: 'image/jpeg' }),
  895. })
  896. core.setFileState(id, {
  897. error: 'something went wrong',
  898. })
  899. await core.retryAll()
  900. expect(onRetryAll).toHaveBeenCalled()
  901. expect(onUpload).toHaveBeenCalled()
  902. })
  903. it('should not start a new upload if there are no failed files', async () => {
  904. const onUpload = jest.fn()
  905. const core = new Core()
  906. core.on('upload', onUpload)
  907. core.addFile({
  908. source: 'jest',
  909. name: 'foo.jpg',
  910. type: 'image/jpeg',
  911. data: new File([sampleImage], { type: 'image/jpeg' }),
  912. })
  913. await core.retryAll()
  914. expect(onUpload).not.toHaveBeenCalled()
  915. })
  916. })
  917. describe('restoring a file', () => {
  918. xit('should restore a file', () => { })
  919. xit("should fail to restore a file if it doesn't exist", () => { })
  920. })
  921. describe('get a file', () => {
  922. it('should get the specified file', () => {
  923. const core = new Core()
  924. core.addFile({
  925. source: 'jest',
  926. name: 'foo.jpg',
  927. type: 'image/jpeg',
  928. data: new File([sampleImage], { type: 'image/jpeg' }),
  929. })
  930. const fileId = Object.keys(core.getState().files)[0]
  931. expect(core.getFile(fileId).name).toEqual('foo.jpg')
  932. expect(core.getFile('non existant file')).toEqual(undefined)
  933. })
  934. })
  935. describe('getFiles', () => {
  936. it('should return an empty array if there are no files', () => {
  937. const core = new Core()
  938. expect(core.getFiles()).toEqual([])
  939. })
  940. it('should return all files as an array', () => {
  941. const core = new Core()
  942. core.addFile({
  943. source: 'jest',
  944. name: 'foo.jpg',
  945. type: 'image/jpeg',
  946. data: new File([sampleImage], { type: 'image/jpeg' }),
  947. })
  948. core.addFile({
  949. source: 'jest',
  950. name: 'empty.dat',
  951. type: 'application/octet-stream',
  952. data: new File([Buffer.alloc(1000)], { type: 'application/octet-stream' }),
  953. })
  954. expect(core.getFiles()).toHaveLength(2)
  955. expect(core.getFiles().map((file) => file.name).sort()).toEqual(['empty.dat', 'foo.jpg'])
  956. })
  957. })
  958. describe('setOptions', () => {
  959. it('should change options on the fly', () => {
  960. const core = new Core()
  961. core.setOptions({
  962. id: 'lolUppy',
  963. autoProceed: true,
  964. allowMultipleUploadBatches: true,
  965. })
  966. expect(core.opts.id).toEqual('lolUppy')
  967. expect(core.opts.autoProceed).toEqual(true)
  968. expect(core.opts.allowMultipleUploadBatches).toEqual(true)
  969. })
  970. it('should change locale on the fly', () => {
  971. const core = new Core()
  972. expect(core.i18n('cancel')).toEqual('Cancel')
  973. core.setOptions({
  974. locale: {
  975. strings: {
  976. cancel: 'Отмена',
  977. },
  978. },
  979. })
  980. expect(core.i18n('cancel')).toEqual('Отмена')
  981. expect(core.i18n('logOut')).toEqual('Log out')
  982. })
  983. it('should change meta on the fly', () => {
  984. const core = new Core({
  985. meta: {
  986. foo: 'bar',
  987. },
  988. })
  989. expect(core.state.meta).toMatchObject({
  990. foo: 'bar',
  991. })
  992. core.setOptions({
  993. meta: {
  994. beep: 'boop',
  995. },
  996. })
  997. expect(core.state.meta).toMatchObject({
  998. foo: 'bar',
  999. beep: 'boop',
  1000. })
  1001. })
  1002. it('should change restrictions on the fly', () => {
  1003. const core = new Core({
  1004. restrictions: {
  1005. allowedFileTypes: ['image/jpeg'],
  1006. maxNumberOfFiles: 2,
  1007. },
  1008. })
  1009. try {
  1010. core.addFile({
  1011. source: 'jest',
  1012. name: 'foo1.png',
  1013. type: 'image/png',
  1014. data: new File([sampleImage], { type: 'image/png' }),
  1015. })
  1016. } catch (err) {
  1017. expect(err).toMatchObject(new Error('You can only upload: image/jpeg'))
  1018. }
  1019. core.setOptions({
  1020. restrictions: {
  1021. allowedFileTypes: ['image/png'],
  1022. },
  1023. })
  1024. expect(core.opts.restrictions.allowedFileTypes).toMatchObject(['image/png'])
  1025. expect(() => {
  1026. core.addFile({
  1027. source: 'jest',
  1028. name: 'foo1.png',
  1029. type: 'image/png',
  1030. data: new File([sampleImage], { type: 'image/png' }),
  1031. })
  1032. }).not.toThrow()
  1033. expect(core.getFiles().length).toEqual(1)
  1034. })
  1035. })
  1036. describe('meta data', () => {
  1037. it('should set meta data by calling setMeta', () => {
  1038. // use DeepFrozenStore in some tests to make sure we are not mutating things
  1039. const core = new Core({
  1040. store: DeepFrozenStore(),
  1041. meta: { foo2: 'bar2' },
  1042. })
  1043. core.setMeta({ foo: 'bar', bur: 'mur' })
  1044. core.setMeta({ boo: 'moo', bur: 'fur' })
  1045. expect(core.getState().meta).toEqual({
  1046. foo: 'bar',
  1047. foo2: 'bar2',
  1048. boo: 'moo',
  1049. bur: 'fur',
  1050. })
  1051. })
  1052. it('should update meta data for a file by calling updateMeta', () => {
  1053. const core = new Core()
  1054. core.addFile({
  1055. source: 'jest',
  1056. name: 'foo.jpg',
  1057. type: 'image/jpeg',
  1058. data: new File([sampleImage], { type: 'image/jpeg' }),
  1059. })
  1060. const fileId = Object.keys(core.getState().files)[0]
  1061. core.setFileMeta(fileId, { foo: 'bar', bur: 'mur' })
  1062. core.setFileMeta(fileId, { boo: 'moo', bur: 'fur' })
  1063. expect(core.getFile(fileId).meta).toEqual({
  1064. name: 'foo.jpg',
  1065. type: 'image/jpeg',
  1066. foo: 'bar',
  1067. bur: 'fur',
  1068. boo: 'moo',
  1069. })
  1070. })
  1071. it('should merge meta data when add file', () => {
  1072. const core = new Core({
  1073. meta: { foo2: 'bar2' },
  1074. })
  1075. core.addFile({
  1076. source: 'jest',
  1077. name: 'foo.jpg',
  1078. type: 'image/jpeg',
  1079. meta: {
  1080. resize: 5000,
  1081. },
  1082. data: new File([sampleImage], { type: 'image/jpeg' }),
  1083. })
  1084. const fileId = Object.keys(core.getState().files)[0]
  1085. expect(core.getFile(fileId).meta).toEqual({
  1086. name: 'foo.jpg',
  1087. type: 'image/jpeg',
  1088. foo2: 'bar2',
  1089. resize: 5000,
  1090. })
  1091. })
  1092. })
  1093. describe('progress', () => {
  1094. it('should calculate the progress of a file upload', () => {
  1095. const core = new Core()
  1096. core.addFile({
  1097. source: 'jest',
  1098. name: 'foo.jpg',
  1099. type: 'image/jpeg',
  1100. data: new File([sampleImage], { type: 'image/jpeg' }),
  1101. })
  1102. const fileId = Object.keys(core.getState().files)[0]
  1103. const file = core.getFile(fileId)
  1104. core.emit('upload-progress', file, {
  1105. bytesUploaded: 12345,
  1106. bytesTotal: 17175,
  1107. })
  1108. expect(core.getFile(fileId).progress).toEqual({
  1109. percentage: 72,
  1110. bytesUploaded: 12345,
  1111. bytesTotal: 17175,
  1112. uploadComplete: false,
  1113. uploadStarted: null,
  1114. })
  1115. core.emit('upload-progress', file, {
  1116. bytesUploaded: 17175,
  1117. bytesTotal: 17175,
  1118. })
  1119. core.calculateProgress.flush()
  1120. expect(core.getFile(fileId).progress).toEqual({
  1121. percentage: 100,
  1122. bytesUploaded: 17175,
  1123. bytesTotal: 17175,
  1124. uploadComplete: false,
  1125. uploadStarted: null,
  1126. })
  1127. })
  1128. it('should work with unsized files', async () => {
  1129. const core = new Core()
  1130. let proceedUpload
  1131. let finishUpload
  1132. const promise = new Promise((resolve) => { proceedUpload = resolve })
  1133. const finishPromise = new Promise((resolve) => { finishUpload = resolve })
  1134. core.addUploader(async ([id]) => {
  1135. core.emit('upload-started', core.getFile(id))
  1136. await promise
  1137. core.emit('upload-progress', core.getFile(id), {
  1138. bytesTotal: 3456,
  1139. bytesUploaded: 1234,
  1140. })
  1141. await finishPromise
  1142. core.emit('upload-success', core.getFile(id), { uploadURL: 'lol' })
  1143. })
  1144. core.addFile({
  1145. source: 'instagram',
  1146. name: 'foo.jpg',
  1147. type: 'image/jpeg',
  1148. data: {},
  1149. })
  1150. core.calculateTotalProgress()
  1151. const uploadPromise = core.upload()
  1152. await new Promise((resolve) => core.once('upload-started', resolve))
  1153. expect(core.getFiles()[0].size).toBeNull()
  1154. expect(core.getFiles()[0].progress).toMatchObject({
  1155. bytesUploaded: 0,
  1156. // null indicates unsized
  1157. bytesTotal: null,
  1158. percentage: 0,
  1159. })
  1160. proceedUpload()
  1161. // wait for progress event
  1162. await promise
  1163. expect(core.getFiles()[0].size).toBeNull()
  1164. expect(core.getFiles()[0].progress).toMatchObject({
  1165. bytesUploaded: 1234,
  1166. bytesTotal: 3456,
  1167. percentage: 36,
  1168. })
  1169. expect(core.getState().totalProgress).toBe(36)
  1170. finishUpload()
  1171. // wait for success event
  1172. await finishPromise
  1173. expect(core.getFiles()[0].size).toBe(3456)
  1174. expect(core.getFiles()[0].progress).toMatchObject({
  1175. bytesUploaded: 3456,
  1176. bytesTotal: 3456,
  1177. percentage: 100,
  1178. })
  1179. await uploadPromise
  1180. core.close()
  1181. })
  1182. it('should estimate progress for unsized files', () => {
  1183. const core = new Core()
  1184. core.once('file-added', (file) => {
  1185. core.emit('upload-started', file)
  1186. core.emit('upload-progress', file, {
  1187. bytesTotal: 3456,
  1188. bytesUploaded: 1234,
  1189. })
  1190. })
  1191. core.addFile({
  1192. source: 'instagram',
  1193. name: 'foo.jpg',
  1194. type: 'image/jpeg',
  1195. data: {},
  1196. })
  1197. core.once('file-added', (file) => {
  1198. core.emit('upload-started', file)
  1199. core.emit('upload-progress', file, {
  1200. bytesTotal: null,
  1201. bytesUploaded: null,
  1202. })
  1203. })
  1204. core.addFile({
  1205. source: 'instagram',
  1206. name: 'bar.jpg',
  1207. type: 'image/jpeg',
  1208. data: {},
  1209. })
  1210. core.calculateTotalProgress()
  1211. // foo.jpg at 35%, bar.jpg at 0%
  1212. expect(core.getState().totalProgress).toBe(18)
  1213. core.close()
  1214. })
  1215. it('should calculate the total progress of all file uploads', () => {
  1216. // use DeepFrozenStore in some tests to make sure we are not mutating things
  1217. const core = new Core({
  1218. store: DeepFrozenStore(),
  1219. })
  1220. core.addFile({
  1221. source: 'jest',
  1222. name: 'foo.jpg',
  1223. type: 'image/jpeg',
  1224. data: new File([sampleImage], { type: 'image/jpeg' }),
  1225. })
  1226. core.addFile({
  1227. source: 'jest',
  1228. name: 'foo2.jpg',
  1229. type: 'image/jpeg',
  1230. data: new File([sampleImage], { type: 'image/jpeg' }),
  1231. })
  1232. const [file1, file2] = core.getFiles()
  1233. core.setFileState(file1.id, { progress: { ...file1.progress, uploadStarted: new Date() } })
  1234. core.setFileState(file2.id, { progress: { ...file2.progress, uploadStarted: new Date() } })
  1235. core.emit('upload-progress', core.getFile(file1.id), {
  1236. bytesUploaded: 12345,
  1237. bytesTotal: 17175,
  1238. })
  1239. core.emit('upload-progress', core.getFile(file2.id), {
  1240. bytesUploaded: 10201,
  1241. bytesTotal: 17175,
  1242. })
  1243. core.calculateTotalProgress()
  1244. core.calculateProgress.flush()
  1245. expect(core.getState().totalProgress).toEqual(66)
  1246. })
  1247. it('should reset the progress', () => {
  1248. const resetProgressEvent = jest.fn()
  1249. const core = new Core()
  1250. core.on('reset-progress', resetProgressEvent)
  1251. core.addFile({
  1252. source: 'jest',
  1253. name: 'foo.jpg',
  1254. type: 'image/jpeg',
  1255. data: new File([sampleImage], { type: 'image/jpeg' }),
  1256. })
  1257. core.addFile({
  1258. source: 'jest',
  1259. name: 'foo2.jpg',
  1260. type: 'image/jpeg',
  1261. data: new File([sampleImage], { type: 'image/jpeg' }),
  1262. })
  1263. const [file1, file2] = core.getFiles()
  1264. core.setFileState(file1.id, { progress: { ...file1.progress, uploadStarted: new Date() } })
  1265. core.setFileState(file2.id, { progress: { ...file2.progress, uploadStarted: new Date() } })
  1266. core.emit('upload-progress', core.getFile(file1.id), {
  1267. bytesUploaded: 12345,
  1268. bytesTotal: 17175,
  1269. })
  1270. core.emit('upload-progress', core.getFile(file2.id), {
  1271. bytesUploaded: 10201,
  1272. bytesTotal: 17175,
  1273. })
  1274. core.calculateTotalProgress()
  1275. core.calculateProgress.flush()
  1276. expect(core.getState().totalProgress).toEqual(66)
  1277. core.resetProgress()
  1278. expect(core.getFile(file1.id).progress).toEqual({
  1279. percentage: 0,
  1280. bytesUploaded: 0,
  1281. bytesTotal: 17175,
  1282. uploadComplete: false,
  1283. uploadStarted: null,
  1284. })
  1285. expect(core.getFile(file2.id).progress).toEqual({
  1286. percentage: 0,
  1287. bytesUploaded: 0,
  1288. bytesTotal: 17175,
  1289. uploadComplete: false,
  1290. uploadStarted: null,
  1291. })
  1292. expect(core.getState().totalProgress).toEqual(0)
  1293. expect(resetProgressEvent.mock.calls.length).toEqual(1)
  1294. })
  1295. })
  1296. describe('checkRestrictions', () => {
  1297. it('should enforce the maxNumberOfFiles rule', () => {
  1298. const core = new Core({
  1299. restrictions: {
  1300. maxNumberOfFiles: 1,
  1301. },
  1302. })
  1303. // add 2 files
  1304. core.addFile({
  1305. source: 'jest',
  1306. name: 'foo1.jpg',
  1307. type: 'image/jpeg',
  1308. data: new File([sampleImage], { type: 'image/jpeg' }),
  1309. })
  1310. try {
  1311. core.addFile({
  1312. source: 'jest',
  1313. name: 'foo2.jpg',
  1314. type: 'image/jpeg',
  1315. data: new File([sampleImage], { type: 'image/jpeg' }),
  1316. })
  1317. throw new Error('should have thrown')
  1318. } catch (err) {
  1319. expect(err).toMatchObject(new Error('You can only upload 1 file'))
  1320. expect(core.getState().info[0].message).toEqual('You can only upload 1 file')
  1321. }
  1322. })
  1323. xit('should enforce the minNumberOfFiles rule', () => { })
  1324. it('should enforce the allowedFileTypes rule', () => {
  1325. const core = new Core({
  1326. restrictions: {
  1327. allowedFileTypes: ['image/gif', 'image/png'],
  1328. },
  1329. })
  1330. try {
  1331. core.addFile({
  1332. source: 'jest',
  1333. name: 'foo2.jpg',
  1334. type: 'image/jpeg',
  1335. data: new File([sampleImage], { type: 'image/jpeg' }),
  1336. })
  1337. throw new Error('should have thrown')
  1338. } catch (err) {
  1339. expect(err).toMatchObject(new Error('You can only upload: image/gif, image/png'))
  1340. expect(core.getState().info[0].message).toEqual('You can only upload: image/gif, image/png')
  1341. }
  1342. })
  1343. it('should throw if allowedFileTypes is not an array', () => {
  1344. try {
  1345. const core = new Core({
  1346. restrictions: {
  1347. allowedFileTypes: 'image/gif',
  1348. },
  1349. })
  1350. core.log('hi')
  1351. } catch (err) {
  1352. expect(err).toMatchObject(new Error('`restrictions.allowedFileTypes` must be an array'))
  1353. }
  1354. })
  1355. it('should enforce the allowedFileTypes rule with file extensions', () => {
  1356. const core = new Core({
  1357. restrictions: {
  1358. allowedFileTypes: ['.gif', '.jpg', '.jpeg'],
  1359. },
  1360. })
  1361. try {
  1362. core.addFile({
  1363. source: 'jest',
  1364. name: 'foo2.png',
  1365. type: '',
  1366. data: new File([sampleImage], { type: 'image/jpeg' }),
  1367. })
  1368. throw new Error('should have thrown')
  1369. } catch (err) {
  1370. expect(err).toMatchObject(new Error('You can only upload: .gif, .jpg, .jpeg'))
  1371. expect(core.getState().info[0].message).toEqual('You can only upload: .gif, .jpg, .jpeg')
  1372. }
  1373. expect(() => core.addFile({
  1374. source: 'jest',
  1375. name: 'foo2.JPG',
  1376. type: '',
  1377. data: new File([sampleImage], { type: 'image/jpeg' }),
  1378. }).not.toThrow())
  1379. })
  1380. it('should enforce the maxFileSize rule', () => {
  1381. const core = new Core({
  1382. restrictions: {
  1383. maxFileSize: 1234,
  1384. },
  1385. })
  1386. try {
  1387. core.addFile({
  1388. source: 'jest',
  1389. name: 'foo.jpg',
  1390. type: 'image/jpeg',
  1391. data: new File([sampleImage], { type: 'image/jpeg' }),
  1392. })
  1393. throw new Error('should have thrown')
  1394. } catch (err) {
  1395. expect(err).toMatchObject(new Error('foo.jpg exceeds maximum allowed size of 1.2 KB'))
  1396. expect(core.getState().info[0].message).toEqual('foo.jpg exceeds maximum allowed size of 1.2 KB')
  1397. }
  1398. })
  1399. it('should enforce the minFileSize rule', () => {
  1400. const core = new Core({
  1401. restrictions: {
  1402. minFileSize: 1073741824,
  1403. },
  1404. })
  1405. try {
  1406. core.addFile({
  1407. source: 'jest',
  1408. name: 'foo.jpg',
  1409. type: 'image/jpeg',
  1410. data: new File([sampleImage], { type: 'image/jpeg' }),
  1411. })
  1412. throw new Error('should have thrown')
  1413. } catch (err) {
  1414. expect(err).toMatchObject(new Error('This file is smaller than the allowed size of 1 GB'))
  1415. expect(core.getState().info[0].message).toEqual('This file is smaller than the allowed size of 1 GB')
  1416. }
  1417. })
  1418. it('should enforce the maxTotalFileSize rule', () => {
  1419. const core = new Core({
  1420. restrictions: {
  1421. maxTotalFileSize: 34000,
  1422. },
  1423. })
  1424. core.addFile({
  1425. source: 'jest',
  1426. name: 'foo.jpg',
  1427. type: 'image/jpeg',
  1428. data: new File([sampleImage], { type: 'image/jpeg' }),
  1429. })
  1430. expect(() => {
  1431. core.addFile({
  1432. source: 'jest',
  1433. name: 'foo1.jpg',
  1434. type: 'image/jpeg',
  1435. data: new File([sampleImage], { type: 'image/jpeg' }),
  1436. })
  1437. }).toThrowError(
  1438. new Error('foo1.jpg exceeds maximum allowed size of 33 KB'),
  1439. )
  1440. })
  1441. it('should check if a file validateRestrictions', () => {
  1442. const core = new Core({
  1443. restrictions: {
  1444. minFileSize: 300000,
  1445. },
  1446. })
  1447. const core2 = new Core({
  1448. restrictions: {
  1449. allowedFileTypes: ['image/png'],
  1450. },
  1451. })
  1452. const newFile = {
  1453. source: 'jest',
  1454. name: 'foo1.jpg',
  1455. extension: 'jpg',
  1456. type: 'image/jpeg',
  1457. data: new File([sampleImage], { type: 'image/jpeg' }),
  1458. isFolder: false,
  1459. mimeType: 'image/jpeg',
  1460. modifiedDate: '2016-04-13T15:11:31.204Z',
  1461. size: 270733,
  1462. }
  1463. const validateRestrictions1 = core.validateRestrictions(newFile)
  1464. const validateRestrictions2 = core2.validateRestrictions(newFile)
  1465. expect(validateRestrictions1).toMatchObject(
  1466. {
  1467. result: false,
  1468. reason: 'This file is smaller than the allowed size of 293 KB',
  1469. },
  1470. )
  1471. expect(validateRestrictions2).toMatchObject(
  1472. {
  1473. result: false,
  1474. reason: 'You can only upload: image/png',
  1475. },
  1476. )
  1477. })
  1478. it('should emit `restriction-failed` event when some rule is violated', () => {
  1479. const maxFileSize = 100
  1480. const core = new Core({
  1481. restrictions: {
  1482. maxFileSize,
  1483. },
  1484. })
  1485. const restrictionsViolatedEventMock = jest.fn()
  1486. const file = {
  1487. name: 'test.jpg',
  1488. data: new Blob([Buffer.alloc(2 * maxFileSize)]),
  1489. }
  1490. const errorMessage = core.i18n('exceedsSize', { file: file.name, size: prettierBytes(maxFileSize) })
  1491. try {
  1492. core.on('restriction-failed', restrictionsViolatedEventMock)
  1493. core.addFile(file)
  1494. } catch {
  1495. // Ignore errors
  1496. }
  1497. expect(restrictionsViolatedEventMock.mock.calls.length).toEqual(1)
  1498. expect(restrictionsViolatedEventMock.mock.calls[0][0].name).toEqual(file.name)
  1499. expect(restrictionsViolatedEventMock.mock.calls[0][1].message).toEqual(errorMessage)
  1500. })
  1501. })
  1502. describe('actions', () => {
  1503. it('should update the state when receiving the error event', () => {
  1504. const core = new Core()
  1505. core.emit('error', new Error('foooooo'))
  1506. expect(core.getState().error).toEqual('foooooo')
  1507. })
  1508. it('should update the state when receiving the upload-error event', () => {
  1509. const core = new Core()
  1510. core.setState({
  1511. files: {
  1512. fileId: {
  1513. id: 'fileId',
  1514. name: 'filename',
  1515. },
  1516. },
  1517. })
  1518. core.emit('upload-error', core.getFile('fileId'), new Error('this is the error'))
  1519. expect(core.getState().info).toEqual([{
  1520. message: 'Failed to upload filename',
  1521. details: 'this is the error',
  1522. type: 'error',
  1523. }])
  1524. })
  1525. it('should reset the error state when receiving the upload event', () => {
  1526. const core = new Core()
  1527. core.emit('error', { foo: 'bar' })
  1528. core.emit('upload')
  1529. expect(core.getState().error).toEqual(null)
  1530. })
  1531. })
  1532. describe('updateOnlineStatus', () => {
  1533. const RealNavigatorOnline = global.window.navigator.onLine
  1534. function mockNavigatorOnline (status) {
  1535. Object.defineProperty(
  1536. global.window.navigator,
  1537. 'onLine',
  1538. {
  1539. value: status,
  1540. writable: true,
  1541. },
  1542. )
  1543. }
  1544. afterEach(() => {
  1545. global.window.navigator.onLine = RealNavigatorOnline
  1546. })
  1547. it('should emit the correct event based on whether there is a network connection', () => {
  1548. const onlineEventMock = jest.fn()
  1549. const offlineEventMock = jest.fn()
  1550. const backOnlineEventMock = jest.fn()
  1551. const core = new Core()
  1552. core.on('is-offline', offlineEventMock)
  1553. core.on('is-online', onlineEventMock)
  1554. core.on('back-online', backOnlineEventMock)
  1555. mockNavigatorOnline(true)
  1556. core.updateOnlineStatus()
  1557. expect(onlineEventMock.mock.calls.length).toEqual(1)
  1558. expect(offlineEventMock.mock.calls.length).toEqual(0)
  1559. expect(backOnlineEventMock.mock.calls.length).toEqual(0)
  1560. mockNavigatorOnline(false)
  1561. core.updateOnlineStatus()
  1562. expect(onlineEventMock.mock.calls.length).toEqual(1)
  1563. expect(offlineEventMock.mock.calls.length).toEqual(1)
  1564. expect(backOnlineEventMock.mock.calls.length).toEqual(0)
  1565. mockNavigatorOnline(true)
  1566. core.updateOnlineStatus()
  1567. expect(onlineEventMock.mock.calls.length).toEqual(2)
  1568. expect(offlineEventMock.mock.calls.length).toEqual(1)
  1569. expect(backOnlineEventMock.mock.calls.length).toEqual(1)
  1570. })
  1571. })
  1572. describe('info', () => {
  1573. it('should set a string based message to be displayed infinitely', () => {
  1574. const infoVisibleEvent = jest.fn()
  1575. const core = new Core()
  1576. core.on('info-visible', infoVisibleEvent)
  1577. core.info('This is the message', 'info', 0)
  1578. expect(core.getState().info).toEqual([{
  1579. type: 'info',
  1580. message: 'This is the message',
  1581. details: null,
  1582. }])
  1583. expect(infoVisibleEvent.mock.calls.length).toEqual(1)
  1584. })
  1585. it('should set a object based message to be displayed infinitely', () => {
  1586. const infoVisibleEvent = jest.fn()
  1587. const core = new Core()
  1588. core.on('info-visible', infoVisibleEvent)
  1589. core.info({
  1590. message: 'This is the message',
  1591. details: {
  1592. foo: 'bar',
  1593. },
  1594. }, 'warning', 0)
  1595. expect(core.getState().info).toEqual([{
  1596. type: 'warning',
  1597. message: 'This is the message',
  1598. details: {
  1599. foo: 'bar',
  1600. },
  1601. }])
  1602. expect(infoVisibleEvent.mock.calls.length).toEqual(1)
  1603. })
  1604. it('should set an info message to be displayed for a period of time before hiding', (done) => {
  1605. const infoVisibleEvent = jest.fn()
  1606. const infoHiddenEvent = jest.fn()
  1607. const core = new Core()
  1608. core.on('info-visible', infoVisibleEvent)
  1609. core.on('info-hidden', infoHiddenEvent)
  1610. core.info('This is the message', 'info', 100)
  1611. expect(infoHiddenEvent.mock.calls.length).toEqual(0)
  1612. setTimeout(() => {
  1613. expect(infoHiddenEvent.mock.calls.length).toEqual(1)
  1614. expect(core.getState().info).toEqual([])
  1615. done()
  1616. }, 110)
  1617. })
  1618. it('should hide an info message', () => {
  1619. const infoVisibleEvent = jest.fn()
  1620. const infoHiddenEvent = jest.fn()
  1621. const core = new Core()
  1622. core.on('info-visible', infoVisibleEvent)
  1623. core.on('info-hidden', infoHiddenEvent)
  1624. core.info('This is the message', 'info', 0)
  1625. expect(infoHiddenEvent.mock.calls.length).toEqual(0)
  1626. core.hideInfo()
  1627. expect(infoHiddenEvent.mock.calls.length).toEqual(1)
  1628. expect(core.getState().info).toEqual([])
  1629. })
  1630. it('should support multiple messages', () => {
  1631. const infoVisibleEvent = jest.fn()
  1632. const infoHiddenEvent = jest.fn()
  1633. const core = new Core()
  1634. core.on('info-visible', infoVisibleEvent)
  1635. core.on('info-hidden', infoHiddenEvent)
  1636. core.info('This is the message', 'info', 0)
  1637. core.info('But this is another one', 'info', 0)
  1638. expect(infoHiddenEvent.mock.calls.length).toEqual(0)
  1639. expect(core.getState().info).toEqual([
  1640. {
  1641. type: 'info',
  1642. message: 'This is the message',
  1643. details: null,
  1644. },
  1645. {
  1646. type: 'info',
  1647. message: 'But this is another one',
  1648. details: null,
  1649. },
  1650. ])
  1651. core.hideInfo()
  1652. expect(core.getState().info).toEqual([
  1653. {
  1654. type: 'info',
  1655. message: 'But this is another one',
  1656. details: null,
  1657. },
  1658. ])
  1659. core.hideInfo()
  1660. expect(infoHiddenEvent.mock.calls.length).toEqual(2)
  1661. expect(core.getState().info).toEqual([])
  1662. })
  1663. })
  1664. describe('createUpload', () => {
  1665. it('should assign the specified files to a new upload', () => {
  1666. const core = new Core()
  1667. core.addFile({
  1668. source: 'jest',
  1669. name: 'foo.jpg',
  1670. type: 'image/jpeg',
  1671. data: new File([sampleImage], { type: 'image/jpeg' }),
  1672. })
  1673. core[Symbol.for('uppy test: createUpload')](Object.keys(core.getState().files))
  1674. const uploadId = Object.keys(core.getState().currentUploads)[0]
  1675. const currentUploadsState = {}
  1676. currentUploadsState[uploadId] = {
  1677. fileIDs: Object.keys(core.getState().files),
  1678. step: 0,
  1679. result: {},
  1680. }
  1681. expect(core.getState().currentUploads).toEqual(currentUploadsState)
  1682. })
  1683. })
  1684. describe('i18n', () => {
  1685. it('merges in custom locale strings', () => {
  1686. const core = new Core({
  1687. locale: {
  1688. strings: {
  1689. test: 'beep boop',
  1690. },
  1691. },
  1692. })
  1693. expect(core.i18n('exceedsSize')).toBe('%{file} exceeds maximum allowed size of %{size}')
  1694. expect(core.i18n('test')).toBe('beep boop')
  1695. })
  1696. })
  1697. describe('default restrictions', () => {
  1698. it('should be merged with supplied restrictions', () => {
  1699. const core = new Core({
  1700. restrictions: {
  1701. maxNumberOfFiles: 3,
  1702. },
  1703. })
  1704. expect(core.opts.restrictions.maxNumberOfFiles).toBe(3)
  1705. expect(core.opts.restrictions.minNumberOfFiles).toBe(null)
  1706. })
  1707. })
  1708. describe('log', () => {
  1709. it('should log via provided logger function', () => {
  1710. const myTestLogger = {
  1711. debug: jest.fn(),
  1712. warn: jest.fn(),
  1713. error: jest.fn(),
  1714. }
  1715. const core = new Core({
  1716. logger: myTestLogger,
  1717. })
  1718. core.log('test test')
  1719. core.log('test test', 'error')
  1720. core.log('test test', 'error')
  1721. core.log('test test', 'warning')
  1722. // logger.debug should have been called 1 time above,
  1723. // but we call log in Core’s constructor to output VERSION, hence +1 here
  1724. expect(core.opts.logger.debug.mock.calls.length).toBe(2)
  1725. expect(core.opts.logger.error.mock.calls.length).toBe(2)
  1726. expect(core.opts.logger.warn.mock.calls.length).toBe(1)
  1727. })
  1728. it('should log via provided logger function, even if debug: true', () => {
  1729. const myTestLogger = {
  1730. debug: jest.fn(),
  1731. warn: jest.fn(),
  1732. error: jest.fn(),
  1733. }
  1734. const core = new Core({
  1735. logger: myTestLogger,
  1736. debug: true,
  1737. })
  1738. core.log('test test')
  1739. core.log('test test', 'error')
  1740. core.log('test test', 'error')
  1741. core.log('test test', 'warning')
  1742. // logger.debug should have been called 1 time above,
  1743. // but we call log in Core’s constructor to output VERSION, hence +1 here
  1744. expect(core.opts.logger.debug.mock.calls.length).toBe(2)
  1745. expect(core.opts.logger.error.mock.calls.length).toBe(2)
  1746. // logger.warn should have been called 1 time above,
  1747. // but we warn in Core when using both logger and debug: true, hence +1 here
  1748. expect(core.opts.logger.warn.mock.calls.length).toBe(2)
  1749. })
  1750. it('should log to console when logger: Uppy.debugLogger or debug: true is set', () => {
  1751. console.debug = jest.fn()
  1752. console.error = jest.fn()
  1753. const core = new Core({
  1754. logger: Core.debugLogger,
  1755. })
  1756. core.log('test test')
  1757. core.log('beep boop')
  1758. core.log('beep beep', 'error')
  1759. // console.debug debug should have been called 2 times above,
  1760. // ibut we call log n Core’ constructor to output VERSION, hence +1 here
  1761. expect(console.debug.mock.calls.length).toBe(3)
  1762. expect(console.error.mock.calls.length).toBe(1)
  1763. console.debug.mockClear()
  1764. console.error.mockClear()
  1765. const core2 = new Core({
  1766. debug: true,
  1767. })
  1768. core2.log('test test')
  1769. core2.log('beep boop')
  1770. core2.log('beep beep', 'error')
  1771. // console.debug debug should have been called 2 times here,
  1772. // but we call log in Core constructor to output VERSION, hence +1 here
  1773. expect(console.debug.mock.calls.length).toBe(3)
  1774. expect(console.error.mock.calls.length).toBe(1)
  1775. })
  1776. it('should only log errors to console when logger is not set', () => {
  1777. console.debug = jest.fn()
  1778. console.error = jest.fn()
  1779. const core = new Core()
  1780. core.log('test test')
  1781. core.log('beep boop')
  1782. core.log('beep beep', 'error')
  1783. expect(console.debug.mock.calls.length).toBe(0)
  1784. expect(console.error.mock.calls.length).toBe(1)
  1785. })
  1786. })
  1787. })