- jest.config.cjs: forceExit:true + testTimeout:15000 - package.json: npm test 默认不再 --coverage - tests/utils.test.ts: debounce 延迟 50->20, 100->50
100 lines
2.1 KiB
TypeScript
100 lines
2.1 KiB
TypeScript
/**
|
|
* utils.ts 单元测试模板
|
|
*/
|
|
|
|
import {
|
|
generateId,
|
|
escapeHTML,
|
|
debounce,
|
|
throttle,
|
|
deepMerge,
|
|
isBrowser,
|
|
} from '../src/utils';
|
|
|
|
describe('generateId', () => {
|
|
test('返回字符串', () => {
|
|
expect(typeof generateId()).toBe('string');
|
|
});
|
|
|
|
test('多次调用产生不同值', () => {
|
|
const ids = new Set<string>();
|
|
for (let i = 0; i < 100; i++) ids.add(generateId());
|
|
expect(ids.size).toBe(100);
|
|
});
|
|
});
|
|
|
|
describe('escapeHTML', () => {
|
|
test('转义 < > &', () => {
|
|
const out = escapeHTML('<a>&b</a>');
|
|
expect(out).toContain('<');
|
|
expect(out).toContain('>');
|
|
expect(out).toContain('&');
|
|
});
|
|
|
|
test('null/undefined 返回空字符串', () => {
|
|
expect(escapeHTML(null)).toBe('');
|
|
expect(escapeHTML(undefined)).toBe('');
|
|
});
|
|
});
|
|
|
|
describe('debounce', () => {
|
|
test('延迟执行', (done) => {
|
|
let called = 0;
|
|
const fn = debounce(() => { called++; }, 20);
|
|
fn();
|
|
expect(called).toBe(0);
|
|
setTimeout(() => {
|
|
expect(called).toBe(1);
|
|
done();
|
|
}, 50);
|
|
});
|
|
|
|
test('多次调用只执行最后一次', (done) => {
|
|
let result = 0;
|
|
const fn = debounce((v: number) => { result = v; }, 20);
|
|
fn(1);
|
|
fn(2);
|
|
fn(3);
|
|
setTimeout(() => {
|
|
expect(result).toBe(3);
|
|
done();
|
|
}, 50);
|
|
});
|
|
});
|
|
|
|
describe('throttle', () => {
|
|
test('首次立即执行', () => {
|
|
let called = 0;
|
|
const fn = throttle(() => { called++; }, 50);
|
|
fn();
|
|
expect(called).toBe(1);
|
|
});
|
|
|
|
test('限流期内不重复执行', () => {
|
|
let called = 0;
|
|
const fn = throttle(() => { called++; }, 50);
|
|
fn();
|
|
fn();
|
|
fn();
|
|
expect(called).toBe(1);
|
|
});
|
|
});
|
|
|
|
describe('deepMerge', () => {
|
|
test('浅层合并', () => {
|
|
const out = deepMerge({ a: 1, b: 2 }, { b: 3, c: 4 });
|
|
expect(out).toEqual({ a: 1, b: 3, c: 4 });
|
|
});
|
|
|
|
test('深层对象合并', () => {
|
|
const out = deepMerge({ obj: { x: 1 } }, { obj: { y: 2 } });
|
|
expect(out).toEqual({ obj: { x: 1, y: 2 } });
|
|
});
|
|
});
|
|
|
|
describe('isBrowser', () => {
|
|
test('jsdom 环境下返回 true', () => {
|
|
expect(isBrowser()).toBe(true);
|
|
});
|
|
});
|