chore: v2.0.1 - 精简dead code + 版本升级

- utils.js: 950行→180行,移除30+未使用函数
- styles.js: 1800行→650行,移除未使用组件样式和重复规则
- animations.js: 850行→120行,移除Web Animations API dead code
- 全项目版本号升级到 2.0.1
- 测试同步清理,134/134通过
This commit is contained in:
2026-07-23 13:18:24 +08:00
parent 5843cff430
commit b4ffaabedd
17 changed files with 280 additions and 3880 deletions
+4 -613
View File
@@ -1,7 +1,7 @@
/**
* MetonaToast 单元测试
* @module tests
* @version 2.0.0
* @version 2.0.1
*/
import MeToast, { Toast, VERSION } from '../src/index.js';
@@ -121,8 +121,8 @@ describe('MetonaToast', () => {
describe('版本信息', () => {
test('应该有正确的版本号', () => {
expect(VERSION).toBe('2.0.0');
expect(MeToast.version).toBe('2.0.0');
expect(VERSION).toBe('2.0.1');
expect(MeToast.version).toBe('2.0.1');
});
});
@@ -583,7 +583,7 @@ describe('MetonaToast', () => {
MeToast.success('消息');
const status = MeToast.getStatus();
expect(status.version).toBe('2.0.0');
expect(status.version).toBe('2.0.1');
expect(status.toasts).toBeGreaterThanOrEqual(0);
expect(status.theme).toBeDefined();
expect(status.locale).toBeDefined();
@@ -776,542 +776,6 @@ describe('工具函数', () => {
const result = prefersDark();
expect(typeof result).toBe('boolean');
});
test('应该能够防抖函数', (done) => {
const { debounce } = require('../src/utils.js');
let count = 0;
const fn = jest.fn(() => count++);
const debouncedFn = debounce(fn, 100);
debouncedFn();
debouncedFn();
debouncedFn();
expect(fn).not.toHaveBeenCalled();
setTimeout(() => {
expect(fn).toHaveBeenCalledTimes(1);
done();
}, 150);
});
test('应该能够节流函数', (done) => {
const { throttle } = require('../src/utils.js');
let count = 0;
const fn = jest.fn(() => count++);
const throttledFn = throttle(fn, 100);
throttledFn();
throttledFn();
throttledFn();
expect(fn).toHaveBeenCalledTimes(1);
setTimeout(() => {
throttledFn();
expect(fn).toHaveBeenCalledTimes(2);
done();
}, 150);
});
test('应该能够深度合并对象', () => {
const { deepMerge } = require('../src/utils.js');
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 3 }, e: 4 };
const merged = deepMerge(obj1, obj2);
expect(merged.a).toBe(1);
expect(merged.b.c).toBe(2);
expect(merged.b.d).toBe(3);
expect(merged.e).toBe(4);
});
test('应该能够检查是否为浏览器环境', () => {
const { isBrowser } = require('../src/utils.js');
const result = isBrowser();
expect(typeof result).toBe('boolean');
});
test('应该能够安全获取嵌套对象属性', () => {
const { getNestedValue } = require('../src/utils.js');
const obj = { a: { b: { c: 1 } } };
expect(getNestedValue(obj, 'a.b.c')).toBe(1);
expect(getNestedValue(obj, 'a.b.d')).toBeUndefined();
expect(getNestedValue(obj, 'a.b.d', 'default')).toBe('default');
});
test('应该能够格式化文件大小', () => {
const { formatFileSize } = require('../src/utils.js');
expect(formatFileSize(0)).toBe('0 Bytes');
expect(formatFileSize(1024)).toBe('1 KB');
expect(formatFileSize(1048576)).toBe('1 MB');
expect(formatFileSize(1073741824)).toBe('1 GB');
});
test('应该能够格式化日期', () => {
const { formatDate } = require('../src/utils.js');
const date = new Date('2024-01-01 12:00:00');
const formatted = formatDate(date, 'YYYY-MM-DD HH:mm:ss');
expect(formatted).toBe('2024-01-01 12:00:00');
});
test('应该能够生成随机数', () => {
const { random } = require('../src/utils.js');
const result = random(1, 100);
expect(result).toBeGreaterThanOrEqual(1);
expect(result).toBeLessThanOrEqual(100);
});
test('应该能够检查元素是否在视口中', () => {
const { isInViewport } = require('../src/utils.js');
const el = {
getBoundingClientRect: () => ({
top: 0,
left: 0,
bottom: 100,
right: 100,
}),
};
expect(isInViewport(el)).toBe(true);
});
test('应该能够复制文本到剪贴板', async () => {
const { copyToClipboard } = require('../src/utils.js');
// Mock clipboard.writeText 返回 resolved promise
if (!navigator.clipboard) navigator.clipboard = {};
const origWriteText = navigator.clipboard.writeText;
navigator.clipboard.writeText = jest.fn(() => Promise.resolve());
const result = await copyToClipboard('test');
expect(result).toBe(true);
navigator.clipboard.writeText = origWriteText;
});
test('应该能够检测设备类型', () => {
const { getDeviceType } = require('../src/utils.js');
const result = getDeviceType();
expect(['desktop', 'mobile', 'tablet']).toContain(result);
});
test('应该能够检测浏览器信息', () => {
const { getBrowserInfo } = require('../src/utils.js');
const result = getBrowserInfo();
expect(result).toBeDefined();
expect(result.browser).toBeDefined();
expect(result.version).toBeDefined();
});
test('应该能够检测操作系统', () => {
const { getOS } = require('../src/utils.js');
const result = getOS();
expect(result).toBeDefined();
});
test('应该能够检测网络状态', () => {
const { getNetworkInfo } = require('../src/utils.js');
const result = getNetworkInfo();
expect(result).toBeDefined();
expect(result.online).toBeDefined();
});
test('应该能够存储和获取数据', () => {
const { setStorage, getStorage, removeStorage } = require('../src/utils.js');
setStorage('test', 'value');
expect(getStorage('test')).toBe('value');
removeStorage('test');
expect(getStorage('test')).toBeNull();
});
test('应该能够生成UUID', () => {
const { generateUUID } = require('../src/utils.js');
const uuid = generateUUID();
expect(uuid).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
});
test('应该能够检查CSS属性支持', () => {
const { supportsCSSProperty } = require('../src/utils.js');
const result = supportsCSSProperty('transform');
expect(typeof result).toBe('boolean');
});
test('应该能够检查JavaScript API支持', () => {
const { supportsAPI } = require('../src/utils.js');
const result = supportsAPI('fetch');
expect(typeof result).toBe('boolean');
});
test('应该能够获取URL参数', () => {
const { getURLParam } = require('../src/utils.js');
// Mock URLSearchParams 来绕过 jsdom location.search 限制
const origSearchParams = global.URLSearchParams;
global.URLSearchParams = jest.fn(() => ({
get: jest.fn((name) => name === 'test' ? 'value' : null),
}));
const result = getURLParam('test');
expect(result).toBe('value');
global.URLSearchParams = origSearchParams;
});
test('应该能够格式化数字', () => {
const { formatNumber } = require('../src/utils.js');
const result = formatNumber(1234567.89, 2);
expect(result).toBeDefined();
});
test('应该能够格式化货币', () => {
const { formatCurrency } = require('../src/utils.js');
const result = formatCurrency(99.99, 'USD');
expect(result).toBeDefined();
});
test('应该能够格式化百分比', () => {
const { formatPercent } = require('../src/utils.js');
const result = formatPercent(75.5, 2);
expect(result).toBeDefined();
});
test('应该能够检查是否为空值', () => {
const { isEmpty } = require('../src/utils.js');
expect(isEmpty(null)).toBe(true);
expect(isEmpty(undefined)).toBe(true);
expect(isEmpty('')).toBe(true);
expect(isEmpty(' ')).toBe(true);
expect(isEmpty([])).toBe(true);
expect(isEmpty({})).toBe(true);
expect(isEmpty('text')).toBe(false);
expect(isEmpty([1])).toBe(false);
expect(isEmpty({ a: 1 })).toBe(false);
});
test('应该能够深拷贝对象', () => {
const { deepClone } = require('../src/utils.js');
const obj = { a: 1, b: { c: 2 }, d: [1, 2, 3] };
const cloned = deepClone(obj);
expect(cloned).toEqual(obj);
expect(cloned).not.toBe(obj);
expect(cloned.b).not.toBe(obj.b);
expect(cloned.d).not.toBe(obj.d);
});
test('应该能够比较对象是否相等', () => {
const { isEqual } = require('../src/utils.js');
expect(isEqual({ a: 1 }, { a: 1 })).toBe(true);
expect(isEqual({ a: 1 }, { a: 2 })).toBe(false);
expect(isEqual({ a: 1, b: 2 }, { a: 1 })).toBe(false);
expect(isEqual([1, 2, 3], [1, 2, 3])).toBe(true);
expect(isEqual([1, 2, 3], [1, 2])).toBe(false);
});
test('应该能够验证邮箱格式', () => {
const { isValidEmail } = require('../src/utils.js');
expect(isValidEmail('test@example.com')).toBe(true);
expect(isValidEmail('invalid-email')).toBe(false);
expect(isValidEmail('test@')).toBe(false);
expect(isValidEmail('@example.com')).toBe(false);
});
test('应该能够验证URL格式', () => {
const { isValidURL } = require('../src/utils.js');
expect(isValidURL('https://example.com')).toBe(true);
expect(isValidURL('http://example.com')).toBe(true);
expect(isValidURL('invalid-url')).toBe(false);
});
test('应该能够验证手机号格式', () => {
const { isValidPhone } = require('../src/utils.js');
expect(isValidPhone('13800138000')).toBe(true);
expect(isValidPhone('12345678901')).toBe(false);
expect(isValidPhone('1380013800')).toBe(false);
});
test('应该能够验证身份证号格式', () => {
const { isValidIDCard } = require('../src/utils.js');
expect(isValidIDCard('110101199003077777')).toBe(true);
expect(isValidIDCard('123456789012345678')).toBe(false);
});
test('应该能够生成随机颜色', () => {
const { randomColor } = require('../src/utils.js');
const color = randomColor();
expect(color).toMatch(/^#[0-9a-f]{6}$/);
});
test('应该能够颜色转RGBA', () => {
const { colorToRGBA } = require('../src/utils.js');
const rgba = colorToRGBA('#ff0000', 0.5);
expect(rgba).toBe('rgba(255, 0, 0, 0.5)');
});
test('应该能够获取颜色亮度', () => {
const { getColorBrightness } = require('../src/utils.js');
const brightness = getColorBrightness('#ffffff');
expect(brightness).toBe(255);
});
test('应该能够判断是否为浅色', () => {
const { isLightColor } = require('../src/utils.js');
expect(isLightColor('#ffffff')).toBe(true);
expect(isLightColor('#000000')).toBe(false);
});
test('应该能够获取对比色', () => {
const { getContrastColor } = require('../src/utils.js');
expect(getContrastColor('#ffffff')).toBe('#000000');
expect(getContrastColor('#000000')).toBe('#FFFFFF');
});
test('应该能够生成渐变色', () => {
const { generateGradient } = require('../src/utils.js');
const gradient = generateGradient('#ff0000', '#0000ff', 5);
expect(gradient).toHaveLength(5);
expect(gradient[0]).toBe('#ff0000');
expect(gradient[4]).toBe('#0000ff');
});
test('应该能够获取字符长度', () => {
const { getStringLength } = require('../src/utils.js');
expect(getStringLength('abc')).toBe(3);
expect(getStringLength('中文')).toBe(4);
expect(getStringLength('abc中文')).toBe(7);
});
test('应该能够截取字符串', () => {
const { truncateString } = require('../src/utils.js');
expect(truncateString('abcdefghij', 5)).toBe('abcde...');
expect(truncateString('中文字符串测试', 8)).toBe('中文字符...');
expect(truncateString('abc', 5)).toBe('abc');
});
test('应该能够驼峰转换', () => {
const { toCamelCase } = require('../src/utils.js');
expect(toCamelCase('hello-world')).toBe('helloWorld');
expect(toCamelCase('hello_world')).toBe('helloWorld');
expect(toCamelCase('hello world')).toBe('helloWorld');
});
test('应该能够短横线转换', () => {
const { toKebabCase } = require('../src/utils.js');
expect(toKebabCase('helloWorld')).toBe('hello-world');
expect(toKebabCase('hello_world')).toBe('hello-world');
expect(toKebabCase('hello world')).toBe('hello-world');
});
test('应该能够下划线转换', () => {
const { toSnakeCase } = require('../src/utils.js');
expect(toSnakeCase('helloWorld')).toBe('hello_world');
expect(toSnakeCase('hello-world')).toBe('hello_world');
expect(toSnakeCase('hello world')).toBe('hello_world');
});
test('应该能够首字母大写', () => {
const { capitalize } = require('../src/utils.js');
expect(capitalize('hello')).toBe('Hello');
expect(capitalize('HELLO')).toBe('HELLO');
});
test('应该能够每个单词首字母大写', () => {
const { capitalizeWords } = require('../src/utils.js');
expect(capitalizeWords('hello world')).toBe('Hello World');
});
test('应该能够移除HTML标签', () => {
const { stripHTML } = require('../src/utils.js');
expect(stripHTML('<b>bold</b>')).toBe('bold');
expect(stripHTML('<p>paragraph</p>')).toBe('paragraph');
});
test('应该能够转义正则表达式', () => {
const { escapeRegExp } = require('../src/utils.js');
expect(escapeRegExp('[test]')).toBe('\\[test\\]');
expect(escapeRegExp('hello.world')).toBe('hello\\.world');
});
test('应该能够生成随机字符串', () => {
const { randomString } = require('../src/utils.js');
const str = randomString(10);
expect(str).toHaveLength(10);
});
test('应该能够延迟执行', async () => {
const { sleep } = require('../src/utils.js');
const start = Date.now();
await sleep(100);
const end = Date.now();
expect(end - start).toBeGreaterThanOrEqual(90);
});
test('应该能够重试函数', async () => {
const { retry } = require('../src/utils.js');
let attempts = 0;
const fn = jest.fn(() => {
attempts++;
if (attempts < 3) {
throw new Error('fail');
}
return 'success';
});
const result = await retry(fn, 3, 10);
expect(result).toBe('success');
expect(fn).toHaveBeenCalledTimes(3);
});
test('应该能够超时控制', async () => {
const { timeout } = require('../src/utils.js');
const promise = new Promise((resolve) => setTimeout(resolve, 200));
await expect(timeout(promise, 100)).rejects.toThrow('Timeout');
});
test('应该能够并发控制', async () => {
const { parallel } = require('../src/utils.js');
const tasks = [
() => Promise.resolve(1),
() => Promise.resolve(2),
() => Promise.resolve(3),
];
const results = await parallel(tasks, 2);
expect(results).toEqual([1, 2, 3]);
});
test('应该能够序列执行', async () => {
const { sequence } = require('../src/utils.js');
const tasks = [
() => Promise.resolve(1),
() => Promise.resolve(2),
() => Promise.resolve(3),
];
const results = await sequence(tasks);
expect(results).toEqual([1, 2, 3]);
});
test('应该能够缓存函数', () => {
const { memoize } = require('../src/utils.js');
let count = 0;
const fn = jest.fn((x) => {
count++;
return x * 2;
});
const memoized = memoize(fn);
expect(memoized(2)).toBe(4);
expect(memoized(2)).toBe(4);
expect(fn).toHaveBeenCalledTimes(1);
});
test('应该能够单例模式', () => {
const { singleton } = require('../src/utils.js');
let count = 0;
const fn = jest.fn(() => {
count++;
return { id: count };
});
const singletonFn = singleton(fn);
const obj1 = singletonFn();
const obj2 = singletonFn();
expect(obj1).toBe(obj2);
expect(fn).toHaveBeenCalledTimes(1);
});
test('应该能够创建观察者', () => {
const { createObserver } = require('../src/utils.js');
const observer = createObserver();
const callback = jest.fn();
observer.on('test', callback);
observer.emit('test', 'data');
expect(callback).toHaveBeenCalledWith('data');
});
test('应该能够创建状态机', () => {
const { createStateMachine } = require('../src/utils.js');
const machine = createStateMachine({
initial: 'idle',
transitions: {
idle: { start: 'running' },
running: { stop: 'idle' },
},
});
expect(machine.state).toBe('idle');
machine.transition('start');
expect(machine.state).toBe('running');
machine.transition('stop');
expect(machine.state).toBe('idle');
});
});
describe('常量', () => {
@@ -1395,79 +859,6 @@ describe('常量', () => {
});
});
describe('动画管理器', () => {
test('应该能够创建动画管理器', () => {
const { createAnimationManager } = require('../src/animations.js');
const manager = createAnimationManager();
expect(manager).toBeDefined();
expect(manager.register).toBeInstanceOf(Function);
expect(manager.apply).toBeInstanceOf(Function);
});
test('应该能够注册动画', () => {
const { createAnimationManager } = require('../src/animations.js');
const manager = createAnimationManager();
manager.register('test', {
enter: { opacity: 0 },
leave: { opacity: 1 },
duration: 300,
});
expect(manager.get('test')).toBeDefined();
});
test('应该能够应用动画', async () => {
const { createAnimationManager } = require('../src/animations.js');
const manager = createAnimationManager();
const element = document.createElement('div');
// 确保 animate 方法存在并在设置 onfinish 后自动调用
element.animate = jest.fn(() => {
const anim = {
onfinish: null,
oncancel: null,
cancel: jest.fn(),
pause: jest.fn(),
play: jest.fn(),
};
// 下一个微任务自动触发 onfinish,让 Promise resolve
Promise.resolve().then(() => {
if (anim.onfinish) anim.onfinish();
});
return anim;
});
manager.register('test', {
enter: { opacity: 0 },
leave: { opacity: 1 },
duration: 100,
});
await manager.apply(element, 'test');
expect(element.animate).toHaveBeenCalled();
});
test('应该能够取消动画', () => {
const { createAnimationManager } = require('../src/animations.js');
const manager = createAnimationManager();
manager.cancelAll();
expect(manager.getActiveCount()).toBe(0);
});
test('应该能够获取活动动画数量', () => {
const { createAnimationManager } = require('../src/animations.js');
const manager = createAnimationManager();
expect(manager.getActiveCount()).toBe(0);
});
});
describe('主题管理器', () => {
test('应该能够获取系统主题', () => {
const { getSystemTheme } = require('../src/themes.js');