|
| 1 | +import { createRequest, createResponse } from 'node-mocks-http'; |
| 2 | +import { parse as parseUrl, URLSearchParams } from 'url'; |
| 3 | +import { EventEmitter } from 'events'; |
| 4 | +import { |
| 5 | + ImageConfig, |
| 6 | + imageConfigDefault, |
| 7 | +} from 'next/dist/next-server/server/image-config'; |
| 8 | + |
| 9 | +import { imageOptimizer } from '../lib/image-optimizer'; |
| 10 | +import { createDeferred } from './utils'; |
| 11 | + |
| 12 | +interface Options { |
| 13 | + w?: string; |
| 14 | + q?: string; |
| 15 | +} |
| 16 | + |
| 17 | +function generateParams(url: string, options: Options = {}) { |
| 18 | + const encodedUrl = encodeURIComponent(url); |
| 19 | + const params = new URLSearchParams(); |
| 20 | + params.append('url', url); |
| 21 | + options.q && params.append('q', options.q); |
| 22 | + options.w && params.append('w', options.w); |
| 23 | + |
| 24 | + const parsedUrl = parseUrl(`/?${params.toString()}`, true); |
| 25 | + |
| 26 | + return { |
| 27 | + url: encodedUrl, |
| 28 | + parsedUrl, |
| 29 | + params: Object.fromEntries(params), |
| 30 | + }; |
| 31 | +} |
| 32 | + |
| 33 | +describe('[unit] imageOptimizer', () => { |
| 34 | + test('', async () => { |
| 35 | + const imageConfig: ImageConfig = { |
| 36 | + ...imageConfigDefault, |
| 37 | + domains: ['upload.wikimedia.org'], |
| 38 | + }; |
| 39 | + |
| 40 | + const params = generateParams( |
| 41 | + 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/4e/Macaca_nigra_self-portrait_large.jpg/1024px-Macaca_nigra_self-portrait_large.jpg', |
| 42 | + { |
| 43 | + w: '2048', |
| 44 | + q: '75', |
| 45 | + } |
| 46 | + ); |
| 47 | + |
| 48 | + // Mock request & response |
| 49 | + const request = createRequest({ |
| 50 | + method: 'GET', |
| 51 | + url: '/image', |
| 52 | + params: params.params, |
| 53 | + }); |
| 54 | + const response = createResponse({ |
| 55 | + eventEmitter: EventEmitter, |
| 56 | + }); |
| 57 | + |
| 58 | + const defer = createDeferred(); |
| 59 | + |
| 60 | + response.on('send', (chunk: any) => { |
| 61 | + console.log(response._getData()); |
| 62 | + }); |
| 63 | + |
| 64 | + response.on('end', () => { |
| 65 | + defer.resolve(); |
| 66 | + }); |
| 67 | + |
| 68 | + const result = await imageOptimizer( |
| 69 | + imageConfig, |
| 70 | + request, |
| 71 | + response, |
| 72 | + params.parsedUrl |
| 73 | + ); |
| 74 | + |
| 75 | + const header = response._getHeaders(); |
| 76 | + const body = response._getBuffer(); |
| 77 | + |
| 78 | + expect(result.finished).toBe(true); |
| 79 | + |
| 80 | + await defer.promise; |
| 81 | + }); |
| 82 | +}); |
0 commit comments