47 lines
1.8 KiB
JavaScript
47 lines
1.8 KiB
JavaScript
/**
|
||
* 功能:验证头像上传成功后的保存重试会复用受控资源地址。
|
||
* 版本:v1.0.0
|
||
*/
|
||
import assert from 'node:assert/strict';
|
||
import { readFile } from 'node:fs/promises';
|
||
import { transformWithOxc } from 'vite';
|
||
|
||
const sourceURL = new URL(
|
||
'../src/views/resource/avatar-upload-cache.ts',
|
||
import.meta.url,
|
||
);
|
||
const source = await readFile(sourceURL, 'utf8');
|
||
const transformed = await transformWithOxc(source, sourceURL.pathname);
|
||
const moduleURL = `data:text/javascript;base64,${Buffer.from(transformed.code).toString('base64')}`;
|
||
const { createAvatarUploadCache } = await import(moduleURL);
|
||
|
||
let uploadCount = 0;
|
||
const cache = createAvatarUploadCache(async () => {
|
||
uploadCount += 1;
|
||
return { uri: `/uploads/avatars/test-${uploadCount}.png` };
|
||
});
|
||
const file = { name: 'avatar.png', size: 128, lastModified: 1 };
|
||
|
||
const firstURI = await cache.resolve(file);
|
||
const retryURI = await cache.resolve(file);
|
||
assert.equal(firstURI, '/uploads/avatars/test-1.png');
|
||
assert.equal(retryURI, firstURI);
|
||
assert.equal(uploadCount, 1, '保存失败后重试不应重复上传同一头像');
|
||
|
||
cache.reset();
|
||
const replacedURI = await cache.resolve(file);
|
||
assert.equal(replacedURI, '/uploads/avatars/test-2.png');
|
||
assert.equal(uploadCount, 2, '重置缓存后应重新上传头像');
|
||
|
||
let failedCount = 0;
|
||
const retryableCache = createAvatarUploadCache(async () => {
|
||
failedCount += 1;
|
||
if (failedCount === 1) throw new Error('临时上传失败');
|
||
return { uri: '/uploads/avatars/retry.png' };
|
||
});
|
||
await assert.rejects(() => retryableCache.resolve(file), /临时上传失败/);
|
||
assert.equal(await retryableCache.resolve(file), '/uploads/avatars/retry.png');
|
||
assert.equal(failedCount, 2, '上传失败后应允许重新上传');
|
||
|
||
console.log('头像失败重试缓存检查通过');
|