File size: 2,003 Bytes
6822ee4
 
747e1c6
6822ee4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747e1c6
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { describe, it, expect } from 'vitest'
import sharp from 'sharp'
import { compressImage, validateImage } from './image-processing.js'

async function makeNoiseImageBase64(width: number, height: number, quality = 100): Promise<string> {
  const channels = 3
  const pixels = Buffer.alloc(width * height * channels)
  for (let i = 0; i < pixels.length; i++) pixels[i] = Math.floor(Math.random() * 256)
  const buf = await sharp(pixels, { raw: { width, height, channels } }).jpeg({ quality }).toBuffer()
  return buf.toString('base64')
}

describe('compressImage', () => {
  it('resizes an oversized image down to a 1800px long edge and shrinks its byte size', async () => {
    const input = await makeNoiseImageBase64(3000, 2000)
    const output = await compressImage(input)
    const meta = await sharp(Buffer.from(output, 'base64')).metadata()
    expect(Math.max(meta.width ?? 0, meta.height ?? 0)).toBe(1800)
    expect(output.length).toBeLessThan(input.length)
  })

  it('leaves a smaller-than-1800px image unscaled', async () => {
    const input = await makeNoiseImageBase64(800, 600)
    const output = await compressImage(input)
    const meta = await sharp(Buffer.from(output, 'base64')).metadata()
    expect(meta.width).toBe(800)
    expect(meta.height).toBe(600)
  })

  it('re-encodes as JPEG regardless of input format', async () => {
    const input = await makeNoiseImageBase64(400, 300)
    const output = await compressImage(input)
    const meta = await sharp(Buffer.from(output, 'base64')).metadata()
    expect(meta.format).toBe('jpeg')
  })
})

describe('validateImage', () => {
  it('resolves for a real, decodable image', async () => {
    const input = await makeNoiseImageBase64(100, 100)
    await expect(validateImage(input)).resolves.toBeUndefined()
  })

  it('rejects bytes that are not a decodable image', async () => {
    const garbage = Buffer.from('this is not an image').toString('base64')
    await expect(validateImage(garbage)).rejects.toThrow()
  })
})