image-picker.test.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { compressPickedImages } from '../../utils/image-picker'
  2. function run(paths, files) {
  3. return new Promise(resolve => {
  4. compressPickedImages(paths, files, resolve)
  5. })
  6. }
  7. describe('image-picker 上传前压缩', () => {
  8. afterEach(() => {
  9. delete global.uni
  10. })
  11. it('小于 800KB 的图片不压缩', async () => {
  12. global.uni = { compressImage: jest.fn() }
  13. const result = await run(['a.jpg'], [{ size: 100 * 1024 }])
  14. expect(result).toEqual(['a.jpg'])
  15. expect(global.uni.compressImage).not.toHaveBeenCalled()
  16. })
  17. it('大图压缩成功时返回压缩后的临时路径', async () => {
  18. global.uni = {
  19. compressImage: jest.fn(opts => opts.success({ tempFilePath: 'a-compressed.jpg' }))
  20. }
  21. const result = await run(['a.jpg'], [{ size: 6 * 1024 * 1024 }])
  22. expect(result).toEqual(['a-compressed.jpg'])
  23. expect(global.uni.compressImage).toHaveBeenCalledWith(expect.objectContaining({
  24. src: 'a.jpg',
  25. quality: 75
  26. }))
  27. })
  28. it('压缩失败时回退原图', async () => {
  29. global.uni = {
  30. compressImage: jest.fn(opts => opts.fail(new Error('compress failed')))
  31. }
  32. const result = await run(['a.jpg'], [{ size: 6 * 1024 * 1024 }])
  33. expect(result).toEqual(['a.jpg'])
  34. })
  35. it('未知大小或缺少压缩 API 时不影响选择结果', async () => {
  36. global.uni = {}
  37. const result = await run(['a.jpg', 'b.png'], [{}, {}])
  38. expect(result).toEqual(['a.jpg', 'b.png'])
  39. })
  40. })