Skip to content

Commit f28ffbd

Browse files
committed
test: add Sharp image snapshot helper
1 parent e135ee1 commit f28ffbd

2 files changed

Lines changed: 19 additions & 19 deletions

File tree

test/utils.tsx

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { join } from 'path'
33
import { Resvg } from '@resvg/resvg-js'
44
import { toMatchImageSnapshot } from 'jest-image-snapshot'
55
import { readFile } from 'node:fs/promises'
6+
import Sharp from 'sharp'
67

78
import { type SatoriOptions } from '../src/index.js'
89

@@ -57,6 +58,22 @@ export function toImage(svg: string, width = 100) {
5758
return pngData.asPng()
5859
}
5960

61+
export async function toImageWithSharp(svg: string, width = 100) {
62+
const webpDataUris = svg.match(/data:image\/webp;base64,[^"']+/g) || []
63+
64+
for (const dataUri of webpDataUris) {
65+
// Resvg cannot decode embedded WebP, so transcode only the image payload.
66+
const webp = Buffer.from(dataUri.slice(dataUri.indexOf(',') + 1), 'base64')
67+
const png = await Sharp(webp).png().toBuffer()
68+
svg = svg.replace(
69+
dataUri,
70+
`data:image/png;base64,${png.toString('base64')}`
71+
)
72+
}
73+
74+
return toImage(svg, width)
75+
}
76+
6077
declare global {
6178
namespace jest {
6279
interface Matchers<R> {

test/webp.test.tsx

Lines changed: 2 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import { describe, expect, it } from 'vitest'
2-
import Sharp from 'sharp'
32

43
import satori from '../src/index.js'
54
import { resolveImageData } from '../src/handler/image.js'
6-
import { toImage } from './utils.js'
5+
import { toImageWithSharp } from './utils.js'
76

87
const WEBP_CASES = [
98
[
@@ -30,30 +29,14 @@ function decodeBase64(data: string) {
3029
return Uint8Array.from(atob(data), (char) => char.charCodeAt(0)).buffer
3130
}
3231

33-
async function toImageWithWebP(svg: string, width: number) {
34-
const webpDataUris = svg.match(/data:image\/webp;base64,[^"']+/g) || []
35-
36-
for (const dataUri of webpDataUris) {
37-
// Resvg cannot decode embedded WebP, so transcode only the image payload.
38-
const webp = Buffer.from(dataUri.slice(dataUri.indexOf(',') + 1), 'base64')
39-
const png = await Sharp(webp).png().toBuffer()
40-
svg = svg.replace(
41-
dataUri,
42-
`data:image/png;base64,${png.toString('base64')}`
43-
)
44-
}
45-
46-
return toImage(svg, width)
47-
}
48-
4932
describe('WebP images', () => {
5033
it.each(WEBP_CASES)('renders %s images', async (_, data, width, height) => {
5134
const svg = await satori(<img src={`data:image/webp;base64,${data}`} />, {
5235
width,
5336
height,
5437
fonts: [],
5538
})
56-
expect(await toImageWithWebP(svg, width * 10)).toMatchImageSnapshot()
39+
expect(await toImageWithSharp(svg, width * 10)).toMatchImageSnapshot()
5740
})
5841

5942
it.each(WEBP_CASES)(

0 commit comments

Comments
 (0)