chore: code format

This commit is contained in:
xiaojunnuo
2025-06-29 14:09:09 +08:00
parent 04422a4637
commit 4fcfd089d8
644 changed files with 10845 additions and 13184 deletions
@@ -1,129 +1,129 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { beforeEach, describe, expect, it, vi } from "vitest";
import { StorageManager } from '../storage-manager';
import { StorageManager } from "../storage-manager";
describe('storageManager', () => {
describe("storageManager", () => {
let storageManager: StorageManager;
beforeEach(() => {
vi.useFakeTimers();
localStorage.clear();
storageManager = new StorageManager({
prefix: 'test_',
prefix: "test_",
});
});
it('should set and get an item', () => {
storageManager.setItem('user', { age: 30, name: 'John Doe' });
const user = storageManager.getItem('user');
expect(user).toEqual({ age: 30, name: 'John Doe' });
it("should set and get an item", () => {
storageManager.setItem("user", { age: 30, name: "John Doe" });
const user = storageManager.getItem("user");
expect(user).toEqual({ age: 30, name: "John Doe" });
});
it('should return default value if item does not exist', () => {
const user = storageManager.getItem('nonexistent', {
it("should return default value if item does not exist", () => {
const user = storageManager.getItem("nonexistent", {
age: 0,
name: 'Default User',
name: "Default User",
});
expect(user).toEqual({ age: 0, name: 'Default User' });
expect(user).toEqual({ age: 0, name: "Default User" });
});
it('should remove an item', () => {
storageManager.setItem('user', { age: 30, name: 'John Doe' });
storageManager.removeItem('user');
const user = storageManager.getItem('user');
it("should remove an item", () => {
storageManager.setItem("user", { age: 30, name: "John Doe" });
storageManager.removeItem("user");
const user = storageManager.getItem("user");
expect(user).toBeNull();
});
it('should clear all items with the prefix', () => {
storageManager.setItem('user1', { age: 30, name: 'John Doe' });
storageManager.setItem('user2', { age: 25, name: 'Jane Doe' });
it("should clear all items with the prefix", () => {
storageManager.setItem("user1", { age: 30, name: "John Doe" });
storageManager.setItem("user2", { age: 25, name: "Jane Doe" });
storageManager.clear();
expect(storageManager.getItem('user1')).toBeNull();
expect(storageManager.getItem('user2')).toBeNull();
expect(storageManager.getItem("user1")).toBeNull();
expect(storageManager.getItem("user2")).toBeNull();
});
it('should clear expired items', () => {
storageManager.setItem('user', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
it("should clear expired items", () => {
storageManager.setItem("user", { age: 30, name: "John Doe" }, 1000); // 1秒过期
vi.advanceTimersByTime(1001); // 快进时间
storageManager.clearExpiredItems();
const user = storageManager.getItem('user');
const user = storageManager.getItem("user");
expect(user).toBeNull();
});
it('should not clear non-expired items', () => {
storageManager.setItem('user', { age: 30, name: 'John Doe' }, 10_000); // 10秒过期
it("should not clear non-expired items", () => {
storageManager.setItem("user", { age: 30, name: "John Doe" }, 10_000); // 10秒过期
vi.advanceTimersByTime(5000); // 快进时间
storageManager.clearExpiredItems();
const user = storageManager.getItem('user');
expect(user).toEqual({ age: 30, name: 'John Doe' });
const user = storageManager.getItem("user");
expect(user).toEqual({ age: 30, name: "John Doe" });
});
it('should handle JSON parse errors gracefully', () => {
localStorage.setItem('test_user', '{ invalid JSON }');
const user = storageManager.getItem('user', {
it("should handle JSON parse errors gracefully", () => {
localStorage.setItem("test_user", "{ invalid JSON }");
const user = storageManager.getItem("user", {
age: 0,
name: 'Default User',
name: "Default User",
});
expect(user).toEqual({ age: 0, name: 'Default User' });
expect(user).toEqual({ age: 0, name: "Default User" });
});
it('should return null for non-existent items without default value', () => {
const user = storageManager.getItem('nonexistent');
it("should return null for non-existent items without default value", () => {
const user = storageManager.getItem("nonexistent");
expect(user).toBeNull();
});
it('should overwrite existing items', () => {
storageManager.setItem('user', { age: 30, name: 'John Doe' });
storageManager.setItem('user', { age: 25, name: 'Jane Doe' });
const user = storageManager.getItem('user');
expect(user).toEqual({ age: 25, name: 'Jane Doe' });
it("should overwrite existing items", () => {
storageManager.setItem("user", { age: 30, name: "John Doe" });
storageManager.setItem("user", { age: 25, name: "Jane Doe" });
const user = storageManager.getItem("user");
expect(user).toEqual({ age: 25, name: "Jane Doe" });
});
it('should handle items without expiry correctly', () => {
storageManager.setItem('user', { age: 30, name: 'John Doe' });
it("should handle items without expiry correctly", () => {
storageManager.setItem("user", { age: 30, name: "John Doe" });
vi.advanceTimersByTime(5000);
const user = storageManager.getItem('user');
expect(user).toEqual({ age: 30, name: 'John Doe' });
const user = storageManager.getItem("user");
expect(user).toEqual({ age: 30, name: "John Doe" });
});
it('should remove expired items when accessed', () => {
storageManager.setItem('user', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
it("should remove expired items when accessed", () => {
storageManager.setItem("user", { age: 30, name: "John Doe" }, 1000); // 1秒过期
vi.advanceTimersByTime(1001); // 快进时间
const user = storageManager.getItem('user');
const user = storageManager.getItem("user");
expect(user).toBeNull();
});
it('should not remove non-expired items when accessed', () => {
storageManager.setItem('user', { age: 30, name: 'John Doe' }, 10_000); // 10秒过期
it("should not remove non-expired items when accessed", () => {
storageManager.setItem("user", { age: 30, name: "John Doe" }, 10_000); // 10秒过期
vi.advanceTimersByTime(5000); // 快进时间
const user = storageManager.getItem('user');
expect(user).toEqual({ age: 30, name: 'John Doe' });
const user = storageManager.getItem("user");
expect(user).toEqual({ age: 30, name: "John Doe" });
});
it('should handle multiple items with different expiry times', () => {
storageManager.setItem('user1', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
storageManager.setItem('user2', { age: 25, name: 'Jane Doe' }, 2000); // 2秒过期
it("should handle multiple items with different expiry times", () => {
storageManager.setItem("user1", { age: 30, name: "John Doe" }, 1000); // 1秒过期
storageManager.setItem("user2", { age: 25, name: "Jane Doe" }, 2000); // 2秒过期
vi.advanceTimersByTime(1500); // 快进时间
storageManager.clearExpiredItems();
const user1 = storageManager.getItem('user1');
const user2 = storageManager.getItem('user2');
const user1 = storageManager.getItem("user1");
const user2 = storageManager.getItem("user2");
expect(user1).toBeNull();
expect(user2).toEqual({ age: 25, name: 'Jane Doe' });
expect(user2).toEqual({ age: 25, name: "Jane Doe" });
});
it('should handle items with no expiry', () => {
storageManager.setItem('user', { age: 30, name: 'John Doe' });
it("should handle items with no expiry", () => {
storageManager.setItem("user", { age: 30, name: "John Doe" });
vi.advanceTimersByTime(10_000); // 快进时间
storageManager.clearExpiredItems();
const user = storageManager.getItem('user');
expect(user).toEqual({ age: 30, name: 'John Doe' });
const user = storageManager.getItem("user");
expect(user).toEqual({ age: 30, name: "John Doe" });
});
it('should clear all items correctly', () => {
storageManager.setItem('user1', { age: 30, name: 'John Doe' });
storageManager.setItem('user2', { age: 25, name: 'Jane Doe' });
it("should clear all items correctly", () => {
storageManager.setItem("user1", { age: 30, name: "John Doe" });
storageManager.setItem("user2", { age: 25, name: "Jane Doe" });
storageManager.clear();
const user1 = storageManager.getItem('user1');
const user2 = storageManager.getItem('user2');
const user1 = storageManager.getItem("user1");
const user2 = storageManager.getItem("user2");
expect(user1).toBeNull();
expect(user2).toBeNull();
});
+1 -1
View File
@@ -1 +1 @@
export * from './storage-manager';
export * from "./storage-manager";
@@ -1,4 +1,4 @@
type StorageType = 'localStorage' | 'sessionStorage';
type StorageType = "localStorage" | "sessionStorage";
interface StorageManagerOptions {
prefix?: string;
@@ -14,15 +14,9 @@ class StorageManager {
private prefix: string;
private storage: Storage;
constructor({
prefix = '',
storageType = 'localStorage',
}: StorageManagerOptions = {}) {
constructor({ prefix = "", storageType = "localStorage" }: StorageManagerOptions = {}) {
this.prefix = prefix;
this.storage =
storageType === 'localStorage'
? window.localStorage
: window.sessionStorage;
this.storage = storageType === "localStorage" ? window.localStorage : window.sessionStorage;
}
/**
@@ -36,7 +30,7 @@ class StorageManager {
keysToRemove.push(key);
}
}
keysToRemove.forEach((key) => this.storage.removeItem(key));
keysToRemove.forEach(key => this.storage.removeItem(key));
}
/**
@@ -46,7 +40,7 @@ class StorageManager {
for (let i = 0; i < this.storage.length; i++) {
const key = this.storage.key(i);
if (key && key.startsWith(this.prefix)) {
const shortKey = key.replace(this.prefix, '');
const shortKey = key.replace(this.prefix, "");
this.getItem(shortKey); // 调用 getItem 方法检查并移除过期项
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
type StorageType = 'localStorage' | 'sessionStorage';
type StorageType = "localStorage" | "sessionStorage";
interface StorageValue<T> {
data: T;
@@ -1,58 +1,53 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import {
convertToHsl,
convertToHslCssVar,
convertToRgb,
isValidColor,
} from '../convert';
import { convertToHsl, convertToHslCssVar, convertToRgb, isValidColor } from "../convert";
describe('color conversion functions', () => {
it('should correctly convert color to HSL format', () => {
const color = '#ff0000';
const expectedHsl = 'hsl(0 100% 50%)';
describe("color conversion functions", () => {
it("should correctly convert color to HSL format", () => {
const color = "#ff0000";
const expectedHsl = "hsl(0 100% 50%)";
expect(convertToHsl(color)).toEqual(expectedHsl);
});
it('should correctly convert color with alpha to HSL format', () => {
const color = 'rgba(255, 0, 0, 0.5)';
const expectedHsl = 'hsl(0 100% 50%) 0.5';
it("should correctly convert color with alpha to HSL format", () => {
const color = "rgba(255, 0, 0, 0.5)";
const expectedHsl = "hsl(0 100% 50%) 0.5";
expect(convertToHsl(color)).toEqual(expectedHsl);
});
it('should correctly convert color to HSL CSS variable format', () => {
const color = '#ff0000';
const expectedHsl = '0 100% 50%';
it("should correctly convert color to HSL CSS variable format", () => {
const color = "#ff0000";
const expectedHsl = "0 100% 50%";
expect(convertToHslCssVar(color)).toEqual(expectedHsl);
});
it('should correctly convert color with alpha to HSL CSS variable format', () => {
const color = 'rgba(255, 0, 0, 0.5)';
const expectedHsl = '0 100% 50% / 0.5';
it("should correctly convert color with alpha to HSL CSS variable format", () => {
const color = "rgba(255, 0, 0, 0.5)";
const expectedHsl = "0 100% 50% / 0.5";
expect(convertToHslCssVar(color)).toEqual(expectedHsl);
});
it('should correctly convert color to RGB CSS variable format', () => {
const color = 'hsl(284, 100%, 50%)';
const expectedRgb = 'rgb(187, 0, 255)';
it("should correctly convert color to RGB CSS variable format", () => {
const color = "hsl(284, 100%, 50%)";
const expectedRgb = "rgb(187, 0, 255)";
expect(convertToRgb(color)).toEqual(expectedRgb);
});
it('should correctly convert color with alpha to RGBA CSS variable format', () => {
const color = 'hsla(284, 100%, 50%, 0.92)';
const expectedRgba = 'rgba(187, 0, 255, 0.92)';
it("should correctly convert color with alpha to RGBA CSS variable format", () => {
const color = "hsla(284, 100%, 50%, 0.92)";
const expectedRgba = "rgba(187, 0, 255, 0.92)";
expect(convertToRgb(color)).toEqual(expectedRgba);
});
});
describe('isValidColor', () => {
it('isValidColor function', () => {
describe("isValidColor", () => {
it("isValidColor function", () => {
// 测试有效颜色
expect(isValidColor('blue')).toBe(true);
expect(isValidColor('#000000')).toBe(true);
expect(isValidColor("blue")).toBe(true);
expect(isValidColor("#000000")).toBe(true);
// 测试无效颜色
expect(isValidColor('invalid color')).toBe(false);
expect(isValidColor("invalid color")).toBe(false);
expect(isValidColor()).toBe(false);
});
});
@@ -1,4 +1,4 @@
import { TinyColor } from '@ctrl/tinycolor';
import { TinyColor } from "@ctrl/tinycolor";
export function isDarkColor(color: string) {
return new TinyColor(color).isDark();
@@ -1,4 +1,4 @@
import { TinyColor } from '@ctrl/tinycolor';
import { TinyColor } from "@ctrl/tinycolor";
/**
* 将颜色转换为HSL格式。
@@ -38,7 +38,7 @@ function convertToHslCssVar(color: string): string {
* @returns 如果颜色值有效,则返回对应的RGB颜色字符串;如果无效,则返回rgb(0, 0, 0)
*/
function convertToRgb(str: string): string {
return new TinyColor(str.replaceAll(/deg|grad|rad|turn/g, '')).toRgbString();
return new TinyColor(str.replaceAll(/deg|grad|rad|turn/g, "")).toRgbString();
}
/**
@@ -53,10 +53,4 @@ function isValidColor(color?: string) {
return new TinyColor(color).isValid;
}
export {
convertToHsl,
convertToHslCssVar,
convertToRgb,
isValidColor,
TinyColor,
};
export { convertToHsl, convertToHslCssVar, convertToRgb, isValidColor, TinyColor };
@@ -1,6 +1,6 @@
import { getColors } from 'theme-colors';
import { getColors } from "theme-colors";
import { convertToHslCssVar, TinyColor } from './convert';
import { convertToHslCssVar, TinyColor } from "./convert";
interface ColorItem {
alias?: string;
@@ -15,11 +15,11 @@ function generatorColorVariables(colorItems: ColorItem[]) {
if (color) {
const colorsMap = getColors(new TinyColor(color).toHexString());
let mainColor = colorsMap['500'];
let mainColor = colorsMap["500"];
const colorKeys = Object.keys(colorsMap);
colorKeys.forEach((key) => {
colorKeys.forEach(key => {
const colorValue = colorsMap[key];
if (colorValue) {
@@ -29,7 +29,7 @@ function generatorColorVariables(colorItems: ColorItem[]) {
colorVariables[`--${alias}-${key}`] = hslColor;
}
if (key === '500') {
if (key === "500") {
mainColor = hslColor;
}
}
@@ -1,3 +1,3 @@
export * from './color';
export * from './convert';
export * from './generator';
export * from "./color";
export * from "./convert";
export * from "./generator";
@@ -13,4 +13,4 @@ export const ELEMENT_ID_MAIN_CONTENT = `__vben_main_content`;
/**
* @zh_CN 默认命名空间
*/
export const DEFAULT_NAMESPACE = 'vben';
export const DEFAULT_NAMESPACE = "vben";
@@ -1,2 +1,2 @@
export * from './globals';
export * from './vben';
export * from "./globals";
export * from "./vben";
@@ -1,26 +1,25 @@
/**
* @zh_CN GITHUB 仓库地址
*/
export const VBEN_GITHUB_URL = 'https://github.com/vbenjs/vue-vben-admin';
export const VBEN_GITHUB_URL = "https://github.com/vbenjs/vue-vben-admin";
/**
* @zh_CN 文档地址
*/
export const VBEN_DOC_URL = 'https://doc.vben.pro';
export const VBEN_DOC_URL = "https://doc.vben.pro";
/**
* @zh_CN Vben Logo
*/
export const VBEN_LOGO_URL =
'https://unpkg.com/@vbenjs/static-source@0.1.7/source/logo-v1.webp';
export const VBEN_LOGO_URL = "https://unpkg.com/@vbenjs/static-source@0.1.7/source/logo-v1.webp";
/**
* @zh_CN Vben Admin 首页地址
*/
export const VBEN_PREVIEW_URL = 'https://www.vben.pro';
export const VBEN_PREVIEW_URL = "https://www.vben.pro";
export const VBEN_ELE_PREVIEW_URL = 'https://ele.vben.pro';
export const VBEN_ELE_PREVIEW_URL = "https://ele.vben.pro";
export const VBEN_NAIVE_PREVIEW_URL = 'https://naive.vben.pro';
export const VBEN_NAIVE_PREVIEW_URL = "https://naive.vben.pro";
export const VBEN_ANT_PREVIEW_URL = 'https://ant.vben.pro';
export const VBEN_ANT_PREVIEW_URL = "https://ant.vben.pro";
@@ -1 +1 @@
export * from '@tanstack/vue-store';
export * from "@tanstack/vue-store";
@@ -1,51 +1,51 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import { diff } from '../diff';
import { diff } from "../diff";
describe('diff function', () => {
it('should return an empty object when comparing identical objects', () => {
describe("diff function", () => {
it("should return an empty object when comparing identical objects", () => {
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { a: 1, b: { c: 2 } };
expect(diff(obj1, obj2)).toEqual(undefined);
});
it('should detect simple changes in primitive values', () => {
it("should detect simple changes in primitive values", () => {
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 3 };
expect(diff(obj1, obj2)).toEqual({ b: 3 });
});
it('should detect nested object changes', () => {
it("should detect nested object changes", () => {
const obj1 = { a: 1, b: { c: 2, d: 4 } };
const obj2 = { a: 1, b: { c: 3, d: 4 } };
expect(diff(obj1, obj2)).toEqual({ b: { c: 3 } });
});
it('should handle array changes', () => {
it("should handle array changes", () => {
const obj1 = { a: [1, 2, 3], b: 2 };
const obj2 = { a: [1, 2, 4], b: 2 };
expect(diff(obj1, obj2)).toEqual({ a: [1, 2, 4] });
});
it('should handle added keys', () => {
it("should handle added keys", () => {
const obj1 = { a: 1 };
const obj2 = { a: 1, b: 2 };
expect(diff(obj1, obj2)).toEqual({ b: 2 });
});
it('should handle removed keys', () => {
it("should handle removed keys", () => {
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1 };
expect(diff(obj1, obj2)).toEqual(undefined);
});
it('should handle boolean value changes', () => {
it("should handle boolean value changes", () => {
const obj1 = { a: true, b: false };
const obj2 = { a: true, b: true };
expect(diff(obj1, obj2)).toEqual({ b: true });
});
it('should handle null and undefined values', () => {
it("should handle null and undefined values", () => {
const obj1 = { a: null, b: undefined };
const obj2: any = { a: 1, b: undefined };
expect(diff(obj1, obj2)).toEqual({ a: 1 });
@@ -1,21 +1,17 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getElementVisibleRect } from '../dom';
import { getElementVisibleRect } from "../dom";
describe('getElementVisibleRect', () => {
describe("getElementVisibleRect", () => {
// 设置浏览器视口尺寸的 mock
beforeEach(() => {
vi.spyOn(document.documentElement, 'clientHeight', 'get').mockReturnValue(
800,
);
vi.spyOn(window, 'innerHeight', 'get').mockReturnValue(800);
vi.spyOn(document.documentElement, 'clientWidth', 'get').mockReturnValue(
1000,
);
vi.spyOn(window, 'innerWidth', 'get').mockReturnValue(1000);
vi.spyOn(document.documentElement, "clientHeight", "get").mockReturnValue(800);
vi.spyOn(window, "innerHeight", "get").mockReturnValue(800);
vi.spyOn(document.documentElement, "clientWidth", "get").mockReturnValue(1000);
vi.spyOn(window, "innerWidth", "get").mockReturnValue(1000);
});
it('should return default rect if element is undefined', () => {
it("should return default rect if element is undefined", () => {
expect(getElementVisibleRect()).toEqual({
bottom: 0,
height: 0,
@@ -26,7 +22,7 @@ describe('getElementVisibleRect', () => {
});
});
it('should return default rect if element is null', () => {
it("should return default rect if element is null", () => {
expect(getElementVisibleRect(null)).toEqual({
bottom: 0,
height: 0,
@@ -37,7 +33,7 @@ describe('getElementVisibleRect', () => {
});
});
it('should return correct visible rect when element is fully visible', () => {
it("should return correct visible rect when element is fully visible", () => {
const element = {
getBoundingClientRect: () => ({
bottom: 400,
@@ -59,7 +55,7 @@ describe('getElementVisibleRect', () => {
});
});
it('should return correct visible rect when element is partially off-screen at the top', () => {
it("should return correct visible rect when element is partially off-screen at the top", () => {
const element = {
getBoundingClientRect: () => ({
bottom: 200,
@@ -81,7 +77,7 @@ describe('getElementVisibleRect', () => {
});
});
it('should return correct visible rect when element is partially off-screen at the right', () => {
it("should return correct visible rect when element is partially off-screen at the right", () => {
const element = {
getBoundingClientRect: () => ({
bottom: 400,
@@ -103,7 +99,7 @@ describe('getElementVisibleRect', () => {
});
});
it('should return all zeros when element is completely off-screen', () => {
it("should return all zeros when element is completely off-screen", () => {
const element = {
getBoundingClientRect: () => ({
bottom: 1200,
@@ -1,127 +1,119 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import {
getFirstNonNullOrUndefined,
isBoolean,
isEmpty,
isHttpUrl,
isObject,
isUndefined,
isWindow,
} from '../inference';
import { getFirstNonNullOrUndefined, isBoolean, isEmpty, isHttpUrl, isObject, isUndefined, isWindow } from "../inference";
describe('isHttpUrl', () => {
describe("isHttpUrl", () => {
it("should return true when given 'http://example.com'", () => {
expect(isHttpUrl('http://example.com')).toBe(true);
expect(isHttpUrl("http://example.com")).toBe(true);
});
it("should return true when given 'https://example.com'", () => {
expect(isHttpUrl('https://example.com')).toBe(true);
expect(isHttpUrl("https://example.com")).toBe(true);
});
it("should return false when given 'ftp://example.com'", () => {
expect(isHttpUrl('ftp://example.com')).toBe(false);
expect(isHttpUrl("ftp://example.com")).toBe(false);
});
it("should return false when given 'example.com'", () => {
expect(isHttpUrl('example.com')).toBe(false);
expect(isHttpUrl("example.com")).toBe(false);
});
});
describe('isUndefined', () => {
it('isUndefined should return true for undefined values', () => {
describe("isUndefined", () => {
it("isUndefined should return true for undefined values", () => {
expect(isUndefined()).toBe(true);
});
it('isUndefined should return false for null values', () => {
it("isUndefined should return false for null values", () => {
expect(isUndefined(null)).toBe(false);
});
it('isUndefined should return false for defined values', () => {
it("isUndefined should return false for defined values", () => {
expect(isUndefined(0)).toBe(false);
expect(isUndefined('')).toBe(false);
expect(isUndefined("")).toBe(false);
expect(isUndefined(false)).toBe(false);
});
it('isUndefined should return false for objects and arrays', () => {
it("isUndefined should return false for objects and arrays", () => {
expect(isUndefined({})).toBe(false);
expect(isUndefined([])).toBe(false);
});
});
describe('isEmpty', () => {
it('should return true for empty string', () => {
expect(isEmpty('')).toBe(true);
describe("isEmpty", () => {
it("should return true for empty string", () => {
expect(isEmpty("")).toBe(true);
});
it('should return true for empty array', () => {
it("should return true for empty array", () => {
expect(isEmpty([])).toBe(true);
});
it('should return true for empty object', () => {
it("should return true for empty object", () => {
expect(isEmpty({})).toBe(true);
});
it('should return false for non-empty string', () => {
expect(isEmpty('hello')).toBe(false);
it("should return false for non-empty string", () => {
expect(isEmpty("hello")).toBe(false);
});
it('should return false for non-empty array', () => {
it("should return false for non-empty array", () => {
expect(isEmpty([1, 2, 3])).toBe(false);
});
it('should return false for non-empty object', () => {
it("should return false for non-empty object", () => {
expect(isEmpty({ a: 1 })).toBe(false);
});
it('should return true for null or undefined', () => {
it("should return true for null or undefined", () => {
expect(isEmpty(null)).toBe(true);
expect(isEmpty()).toBe(true);
});
it('should return false for number or boolean', () => {
it("should return false for number or boolean", () => {
expect(isEmpty(0)).toBe(false);
expect(isEmpty(true)).toBe(false);
});
});
describe('isWindow', () => {
it('should return true for the window object', () => {
describe("isWindow", () => {
it("should return true for the window object", () => {
expect(isWindow(window)).toBe(true);
});
it('should return false for other objects', () => {
it("should return false for other objects", () => {
expect(isWindow({})).toBe(false);
expect(isWindow([])).toBe(false);
expect(isWindow(null)).toBe(false);
});
});
describe('isBoolean', () => {
it('should return true for boolean values', () => {
describe("isBoolean", () => {
it("should return true for boolean values", () => {
expect(isBoolean(true)).toBe(true);
expect(isBoolean(false)).toBe(true);
});
it('should return false for non-boolean values', () => {
it("should return false for non-boolean values", () => {
expect(isBoolean(null)).toBe(false);
expect(isBoolean(42)).toBe(false);
expect(isBoolean('string')).toBe(false);
expect(isBoolean("string")).toBe(false);
expect(isBoolean({})).toBe(false);
expect(isBoolean([])).toBe(false);
});
});
describe('isObject', () => {
it('should return true for objects', () => {
describe("isObject", () => {
it("should return true for objects", () => {
expect(isObject({})).toBe(true);
expect(isObject({ a: 1 })).toBe(true);
});
it('should return false for non-objects', () => {
it("should return false for non-objects", () => {
expect(isObject(null)).toBe(false);
expect(isObject(42)).toBe(false);
expect(isObject('string')).toBe(false);
expect(isObject("string")).toBe(false);
expect(isObject(true)).toBe(false);
expect(isObject([1, 2, 3])).toBe(true);
expect(isObject(new Date())).toBe(true);
@@ -129,55 +121,32 @@ describe('isObject', () => {
});
});
describe('getFirstNonNullOrUndefined', () => {
describe('getFirstNonNullOrUndefined', () => {
it('should return the first non-null and non-undefined value for a number array', () => {
expect(getFirstNonNullOrUndefined<number>(undefined, null, 0, 42)).toBe(
0,
);
expect(getFirstNonNullOrUndefined<number>(null, undefined, 42, 123)).toBe(
42,
);
describe("getFirstNonNullOrUndefined", () => {
describe("getFirstNonNullOrUndefined", () => {
it("should return the first non-null and non-undefined value for a number array", () => {
expect(getFirstNonNullOrUndefined<number>(undefined, null, 0, 42)).toBe(0);
expect(getFirstNonNullOrUndefined<number>(null, undefined, 42, 123)).toBe(42);
});
it('should return the first non-null and non-undefined value for a string array', () => {
expect(
getFirstNonNullOrUndefined<string>(undefined, null, '', 'hello'),
).toBe('');
expect(
getFirstNonNullOrUndefined<string>(null, undefined, 'test', 'world'),
).toBe('test');
it("should return the first non-null and non-undefined value for a string array", () => {
expect(getFirstNonNullOrUndefined<string>(undefined, null, "", "hello")).toBe("");
expect(getFirstNonNullOrUndefined<string>(null, undefined, "test", "world")).toBe("test");
});
it('should return undefined if all values are null or undefined', () => {
it("should return undefined if all values are null or undefined", () => {
expect(getFirstNonNullOrUndefined(undefined, null)).toBeUndefined();
expect(getFirstNonNullOrUndefined(null)).toBeUndefined();
});
it('should work with a single value', () => {
it("should work with a single value", () => {
expect(getFirstNonNullOrUndefined(42)).toBe(42);
expect(getFirstNonNullOrUndefined()).toBeUndefined();
expect(getFirstNonNullOrUndefined(null)).toBeUndefined();
});
it('should handle mixed types correctly', () => {
expect(
getFirstNonNullOrUndefined<number | object | string>(
undefined,
null,
'test',
123,
{ key: 'value' },
),
).toBe('test');
expect(
getFirstNonNullOrUndefined<number | object | string>(
null,
undefined,
[1, 2, 3],
'string',
),
).toEqual([1, 2, 3]);
it("should handle mixed types correctly", () => {
expect(getFirstNonNullOrUndefined<number | object | string>(undefined, null, "test", 123, { key: "value" })).toBe("test");
expect(getFirstNonNullOrUndefined<number | object | string>(null, undefined, [1, 2, 3], "string")).toEqual([1, 2, 3]);
});
});
});
@@ -1,116 +1,109 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import {
capitalizeFirstLetter,
kebabToCamelCase,
toCamelCase,
toLowerCaseFirstLetter,
} from '../letter';
import { capitalizeFirstLetter, kebabToCamelCase, toCamelCase, toLowerCaseFirstLetter } from "../letter";
describe('capitalizeFirstLetter', () => {
it('should capitalize the first letter of a string', () => {
expect(capitalizeFirstLetter('hello')).toBe('Hello');
expect(capitalizeFirstLetter('world')).toBe('World');
describe("capitalizeFirstLetter", () => {
it("should capitalize the first letter of a string", () => {
expect(capitalizeFirstLetter("hello")).toBe("Hello");
expect(capitalizeFirstLetter("world")).toBe("World");
});
it('should handle empty strings', () => {
expect(capitalizeFirstLetter('')).toBe('');
it("should handle empty strings", () => {
expect(capitalizeFirstLetter("")).toBe("");
});
it('should handle single character strings', () => {
expect(capitalizeFirstLetter('a')).toBe('A');
expect(capitalizeFirstLetter('b')).toBe('B');
it("should handle single character strings", () => {
expect(capitalizeFirstLetter("a")).toBe("A");
expect(capitalizeFirstLetter("b")).toBe("B");
});
it('should not change the case of other characters', () => {
expect(capitalizeFirstLetter('hElLo')).toBe('HElLo');
it("should not change the case of other characters", () => {
expect(capitalizeFirstLetter("hElLo")).toBe("HElLo");
});
});
describe('toLowerCaseFirstLetter', () => {
it('should convert the first letter to lowercase', () => {
expect(toLowerCaseFirstLetter('CommonAppName')).toBe('commonAppName');
expect(toLowerCaseFirstLetter('AnotherKeyExample')).toBe(
'anotherKeyExample',
);
describe("toLowerCaseFirstLetter", () => {
it("should convert the first letter to lowercase", () => {
expect(toLowerCaseFirstLetter("CommonAppName")).toBe("commonAppName");
expect(toLowerCaseFirstLetter("AnotherKeyExample")).toBe("anotherKeyExample");
});
it('should return the same string if the first letter is already lowercase', () => {
expect(toLowerCaseFirstLetter('alreadyLowerCase')).toBe('alreadyLowerCase');
it("should return the same string if the first letter is already lowercase", () => {
expect(toLowerCaseFirstLetter("alreadyLowerCase")).toBe("alreadyLowerCase");
});
it('should handle empty strings', () => {
expect(toLowerCaseFirstLetter('')).toBe('');
it("should handle empty strings", () => {
expect(toLowerCaseFirstLetter("")).toBe("");
});
it('should handle single character strings', () => {
expect(toLowerCaseFirstLetter('A')).toBe('a');
expect(toLowerCaseFirstLetter('a')).toBe('a');
it("should handle single character strings", () => {
expect(toLowerCaseFirstLetter("A")).toBe("a");
expect(toLowerCaseFirstLetter("a")).toBe("a");
});
it('should handle strings with only one uppercase letter', () => {
expect(toLowerCaseFirstLetter('A')).toBe('a');
it("should handle strings with only one uppercase letter", () => {
expect(toLowerCaseFirstLetter("A")).toBe("a");
});
it('should handle strings with special characters', () => {
expect(toLowerCaseFirstLetter('!Special')).toBe('!Special');
expect(toLowerCaseFirstLetter('123Number')).toBe('123Number');
it("should handle strings with special characters", () => {
expect(toLowerCaseFirstLetter("!Special")).toBe("!Special");
expect(toLowerCaseFirstLetter("123Number")).toBe("123Number");
});
});
describe('toCamelCase', () => {
it('should return the key if parentKey is empty', () => {
expect(toCamelCase('child', '')).toBe('child');
describe("toCamelCase", () => {
it("should return the key if parentKey is empty", () => {
expect(toCamelCase("child", "")).toBe("child");
});
it('should combine parentKey and key in camel case', () => {
expect(toCamelCase('child', 'parent')).toBe('parentChild');
it("should combine parentKey and key in camel case", () => {
expect(toCamelCase("child", "parent")).toBe("parentChild");
});
it('should handle empty key and parentKey', () => {
expect(toCamelCase('', '')).toBe('');
it("should handle empty key and parentKey", () => {
expect(toCamelCase("", "")).toBe("");
});
it('should handle key with capital letters', () => {
expect(toCamelCase('Child', 'parent')).toBe('parentChild');
expect(toCamelCase('Child', 'Parent')).toBe('ParentChild');
it("should handle key with capital letters", () => {
expect(toCamelCase("Child", "parent")).toBe("parentChild");
expect(toCamelCase("Child", "Parent")).toBe("ParentChild");
});
});
describe('kebabToCamelCase', () => {
it('should convert kebab-case to camelCase correctly', () => {
expect(kebabToCamelCase('my-component-name')).toBe('myComponentName');
describe("kebabToCamelCase", () => {
it("should convert kebab-case to camelCase correctly", () => {
expect(kebabToCamelCase("my-component-name")).toBe("myComponentName");
});
it('should handle multiple consecutive hyphens', () => {
expect(kebabToCamelCase('my--component--name')).toBe('myComponentName');
it("should handle multiple consecutive hyphens", () => {
expect(kebabToCamelCase("my--component--name")).toBe("myComponentName");
});
it('should trim leading and trailing hyphens', () => {
expect(kebabToCamelCase('-my-component-name-')).toBe('myComponentName');
it("should trim leading and trailing hyphens", () => {
expect(kebabToCamelCase("-my-component-name-")).toBe("myComponentName");
});
it('should preserve the case of the first word', () => {
expect(kebabToCamelCase('My-component-name')).toBe('MyComponentName');
it("should preserve the case of the first word", () => {
expect(kebabToCamelCase("My-component-name")).toBe("MyComponentName");
});
it('should convert a single word correctly', () => {
expect(kebabToCamelCase('component')).toBe('component');
it("should convert a single word correctly", () => {
expect(kebabToCamelCase("component")).toBe("component");
});
it('should return an empty string if input is empty', () => {
expect(kebabToCamelCase('')).toBe('');
it("should return an empty string if input is empty", () => {
expect(kebabToCamelCase("")).toBe("");
});
it('should handle strings with no hyphens', () => {
expect(kebabToCamelCase('mycomponentname')).toBe('mycomponentname');
it("should handle strings with no hyphens", () => {
expect(kebabToCamelCase("mycomponentname")).toBe("mycomponentname");
});
it('should handle strings with only hyphens', () => {
expect(kebabToCamelCase('---')).toBe('');
it("should handle strings with only hyphens", () => {
expect(kebabToCamelCase("---")).toBe("");
});
it('should handle mixed case inputs', () => {
expect(kebabToCamelCase('my-Component-Name')).toBe('myComponentName');
it("should handle mixed case inputs", () => {
expect(kebabToCamelCase("my-Component-Name")).toBe("myComponentName");
});
});
@@ -1,9 +1,9 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import { StateHandler } from '../state-handler';
import { StateHandler } from "../state-handler";
describe('stateHandler', () => {
it('should resolve when condition is set to true', async () => {
describe("stateHandler", () => {
it("should resolve when condition is set to true", async () => {
const handler = new StateHandler();
// 模拟异步设置 condition 为 true
@@ -16,7 +16,7 @@ describe('stateHandler', () => {
expect(handler.isConditionTrue()).toBe(true);
});
it('should resolve immediately if condition is already true', async () => {
it("should resolve immediately if condition is already true", async () => {
const handler = new StateHandler();
handler.setConditionTrue(); // 提前设置为 true
@@ -25,7 +25,7 @@ describe('stateHandler', () => {
expect(handler.isConditionTrue()).toBe(true);
});
it('should reject when condition is set to false after waiting', async () => {
it("should reject when condition is set to false after waiting", async () => {
const handler = new StateHandler();
// 模拟异步设置 condition 为 false
@@ -38,7 +38,7 @@ describe('stateHandler', () => {
expect(handler.isConditionTrue()).toBe(false);
});
it('should reset condition to false', () => {
it("should reset condition to false", () => {
const handler = new StateHandler();
handler.setConditionTrue(); // 设置为 true
handler.reset(); // 重置为 false
@@ -46,7 +46,7 @@ describe('stateHandler', () => {
expect(handler.isConditionTrue()).toBe(false);
});
it('should resolve when condition is set to true after reset', async () => {
it("should resolve when condition is set to true after reset", async () => {
const handler = new StateHandler();
handler.reset(); // 确保初始为 false
@@ -17,9 +17,9 @@ describe("traverseTreeValues", () => {
{ name: "B" },
{
name: "C",
children: [{ name: "D" }, { name: "E" }]
}
]
children: [{ name: "D" }, { name: "E" }],
},
],
},
{
name: "F",
@@ -27,33 +27,33 @@ describe("traverseTreeValues", () => {
{ name: "G" },
{
name: "H",
children: [{ name: "I" }]
}
]
}
children: [{ name: "I" }],
},
],
},
];
it("traverses tree and returns all node values", () => {
const values = traverseTreeValues<Node, NodeValue>(sampleTree, (node) => node.name, {
childProps: "children"
const values = traverseTreeValues<Node, NodeValue>(sampleTree, node => node.name, {
childProps: "children",
});
expect(values).toEqual(["A", "B", "C", "D", "E", "F", "G", "H", "I"]);
});
it("handles empty tree", () => {
const values = traverseTreeValues<Node, NodeValue>([], (node) => node.name);
const values = traverseTreeValues<Node, NodeValue>([], node => node.name);
expect(values).toEqual([]);
});
it("handles tree with only root node", () => {
const rootNode = { name: "A" };
const values = traverseTreeValues<Node, NodeValue>([rootNode], (node) => node.name);
const values = traverseTreeValues<Node, NodeValue>([rootNode], node => node.name);
expect(values).toEqual(["A"]);
});
it("handles tree with only leaf nodes", () => {
const leafNodes = [{ name: "A" }, { name: "B" }, { name: "C" }];
const values = traverseTreeValues<Node, NodeValue>(leafNodes, (node) => node.name);
const values = traverseTreeValues<Node, NodeValue>(leafNodes, node => node.name);
expect(values).toEqual(["A", "B", "C"]);
});
});
@@ -62,10 +62,10 @@ describe("filterTree", () => {
const tree = [
{
id: 1,
children: [{ id: 2 }, { id: 3, children: [{ id: 4 }, { id: 5 }, { id: 6 }] }, { id: 7 }]
children: [{ id: 2 }, { id: 3, children: [{ id: 4 }, { id: 5 }, { id: 6 }] }, { id: 7 }],
},
{ id: 8, children: [{ id: 9 }, { id: 10 }] },
{ id: 11 }
{ id: 11 },
];
it("should return all nodes when condition is always true", () => {
@@ -79,18 +79,18 @@ describe("filterTree", () => {
});
it("should return nodes with even id values", () => {
const result = filterTree(tree, (node) => node.id % 2 === 0);
const result = filterTree(tree, node => node.id % 2 === 0);
expect(result).toEqual([{ id: 8, children: [{ id: 10 }] }]);
});
it("should return nodes with odd id values and their ancestors", () => {
const result = filterTree(tree, (node) => node.id % 2 === 1);
const result = filterTree(tree, node => node.id % 2 === 1);
expect(result).toEqual([
{
id: 1,
children: [{ id: 3, children: [{ id: 5 }] }, { id: 7 }]
children: [{ id: 3, children: [{ id: 5 }] }, { id: 7 }],
},
{ id: 11 }
{ id: 11 },
]);
});
@@ -102,18 +102,18 @@ describe("filterTree", () => {
{ name: "leaf 1" },
{
name: "branch",
children: [{ name: "leaf 2" }, { name: "leaf 3" }]
children: [{ name: "leaf 2" }, { name: "leaf 3" }],
},
{ name: "leaf 4" }
]
}
{ name: "leaf 4" },
],
},
];
const result = filterTree(tree, (node) => node.name.includes("leaf") || node.name === "root");
const result = filterTree(tree, node => node.name.includes("leaf") || node.name === "root");
expect(result).toEqual([
{
name: "root",
children: [{ name: "leaf 1" }, { name: "leaf 4" }]
}
children: [{ name: "leaf 1" }, { name: "leaf 4" }],
},
]);
});
});
@@ -136,18 +136,18 @@ describe("mapTree", () => {
name: "node5",
children: [
{ id: 6, name: "node6" },
{ id: 7, name: "node7" }
]
{ id: 7, name: "node7" },
],
},
{ id: 8, name: "node8" }
]
}
]
}
{ id: 8, name: "node8" },
],
},
],
},
];
const newTree = mapTree(tree, (node) => ({
const newTree = mapTree(tree, node => ({
...node,
name: `${node.name}-new`
name: `${node.name}-new`,
}));
expect(newTree).toEqual([
@@ -166,14 +166,14 @@ describe("mapTree", () => {
name: "node5-new",
children: [
{ id: 6, name: "node6-new" },
{ id: 7, name: "node7-new" }
]
{ id: 7, name: "node7-new" },
],
},
{ id: 8, name: "node8-new" }
]
}
]
}
{ id: 8, name: "node8-new" },
],
},
],
},
]);
});
});
@@ -1,60 +1,60 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import { uniqueByField } from '../unique';
import { uniqueByField } from "../unique";
describe('uniqueByField', () => {
it('should return an array with unique items based on id field', () => {
describe("uniqueByField", () => {
it("should return an array with unique items based on id field", () => {
const items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
{ id: 1, name: 'Duplicate Item' },
{ id: 1, name: "Item 1" },
{ id: 2, name: "Item 2" },
{ id: 3, name: "Item 3" },
{ id: 1, name: "Duplicate Item" },
];
const uniqueItems = uniqueByField(items, 'id');
const uniqueItems = uniqueByField(items, "id");
expect(uniqueItems).toHaveLength(3);
expect(uniqueItems).toEqual([
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
{ id: 1, name: "Item 1" },
{ id: 2, name: "Item 2" },
{ id: 3, name: "Item 3" },
]);
});
it('should return an empty array when input array is empty', () => {
it("should return an empty array when input array is empty", () => {
const items: any[] = []; // Empty array
const uniqueItems = uniqueByField(items, 'id');
const uniqueItems = uniqueByField(items, "id");
// Assert expected results
expect(uniqueItems).toEqual([]);
});
it('should handle arrays with only one item correctly', () => {
const items = [{ id: 1, name: 'Item 1' }];
it("should handle arrays with only one item correctly", () => {
const items = [{ id: 1, name: "Item 1" }];
const uniqueItems = uniqueByField(items, 'id');
const uniqueItems = uniqueByField(items, "id");
// Assert expected results
expect(uniqueItems).toHaveLength(1);
expect(uniqueItems).toEqual([{ id: 1, name: 'Item 1' }]);
expect(uniqueItems).toEqual([{ id: 1, name: "Item 1" }]);
});
it('should preserve the order of the first occurrence of each item', () => {
it("should preserve the order of the first occurrence of each item", () => {
const items = [
{ id: 2, name: 'Item 2' },
{ id: 1, name: 'Item 1' },
{ id: 3, name: 'Item 3' },
{ id: 1, name: 'Duplicate Item' },
{ id: 2, name: "Item 2" },
{ id: 1, name: "Item 1" },
{ id: 3, name: "Item 3" },
{ id: 1, name: "Duplicate Item" },
];
const uniqueItems = uniqueByField(items, 'id');
const uniqueItems = uniqueByField(items, "id");
// Assert expected results (order of first occurrences preserved)
expect(uniqueItems).toEqual([
{ id: 2, name: 'Item 2' },
{ id: 1, name: 'Item 1' },
{ id: 3, name: 'Item 3' },
{ id: 2, name: "Item 2" },
{ id: 1, name: "Item 1" },
{ id: 3, name: "Item 3" },
]);
});
});
@@ -1,30 +1,26 @@
import { expect, it } from 'vitest';
import { expect, it } from "vitest";
import { updateCSSVariables } from '../update-css-variables';
import { updateCSSVariables } from "../update-css-variables";
it('updateCSSVariables should update CSS variables in :root selector', () => {
it("updateCSSVariables should update CSS variables in :root selector", () => {
// 模拟初始的内联样式表内容
const initialStyleContent = ':root { --primaryColor: red; }';
const initialStyleContent = ":root { --primaryColor: red; }";
document.head.innerHTML = `<style id="custom-styles">${initialStyleContent}</style>`;
// 要更新的CSS变量和它们的新值
const updatedVariables = {
fontSize: '16px',
primaryColor: 'blue',
secondaryColor: 'green',
fontSize: "16px",
primaryColor: "blue",
secondaryColor: "green",
};
// 调用函数来更新CSS变量
updateCSSVariables(updatedVariables, 'custom-styles');
updateCSSVariables(updatedVariables, "custom-styles");
// 获取更新后的样式内容
const styleElement = document.querySelector('#custom-styles');
const updatedStyleContent = styleElement ? styleElement.textContent : '';
const styleElement = document.querySelector("#custom-styles");
const updatedStyleContent = styleElement ? styleElement.textContent : "";
// 检查更新后的样式内容是否包含正确的更新值
expect(
updatedStyleContent?.includes('primaryColor: blue;') &&
updatedStyleContent?.includes('secondaryColor: green;') &&
updatedStyleContent?.includes('fontSize: 16px;'),
).toBe(true);
expect(updatedStyleContent?.includes("primaryColor: blue;") && updatedStyleContent?.includes("secondaryColor: green;") && updatedStyleContent?.includes("fontSize: 16px;")).toBe(true);
});
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import { bindMethods, getNestedValue } from '../util';
import { bindMethods, getNestedValue } from "../util";
class TestClass {
public value: string;
@@ -19,42 +19,42 @@ class TestClass {
}
}
describe('bindMethods', () => {
it('should bind methods to the instance correctly', () => {
const instance = new TestClass('initial');
describe("bindMethods", () => {
it("should bind methods to the instance correctly", () => {
const instance = new TestClass("initial");
// 解构方法
const { getValue } = instance;
// 检查 getValue 是否能正确调用,并且 this 绑定了 instance
expect(getValue()).toBe('initial');
expect(getValue()).toBe("initial");
});
it('should bind multiple methods', () => {
const instance = new TestClass('initial');
it("should bind multiple methods", () => {
const instance = new TestClass("initial");
const { getValue, setValue } = instance;
// 检查 getValue 和 setValue 方法是否正确绑定了 this
setValue('newValue');
expect(getValue()).toBe('newValue');
setValue("newValue");
expect(getValue()).toBe("newValue");
});
it('should not bind non-function properties', () => {
const instance = new TestClass('initial');
it("should not bind non-function properties", () => {
const instance = new TestClass("initial");
// 检查普通属性是否保持原样
expect(instance.value).toBe('initial');
expect(instance.value).toBe("initial");
});
it('should not bind constructor method', () => {
const instance = new TestClass('test');
it("should not bind constructor method", () => {
const instance = new TestClass("test");
// 检查 constructor 是否没有被绑定
expect(instance.constructor.name).toBe('TestClass');
expect(instance.constructor.name).toBe("TestClass");
});
it('should not bind getter/setter properties', () => {
it("should not bind getter/setter properties", () => {
class TestWithGetterSetter {
get value() {
return this._value;
@@ -64,7 +64,7 @@ describe('bindMethods', () => {
this._value = newValue;
}
private _value: string = 'test';
private _value: string = "test";
constructor() {
bindMethods(this);
@@ -75,11 +75,11 @@ describe('bindMethods', () => {
const { value } = instance;
// Getter 和 setter 不应被绑定
expect(value).toBe('test');
expect(value).toBe("test");
});
});
describe('getNestedValue', () => {
describe("getNestedValue", () => {
interface UserProfile {
age: number;
name: string;
@@ -100,57 +100,57 @@ describe('getNestedValue', () => {
user: {
profile: {
age: 25,
name: 'Alice',
name: "Alice",
},
settings: {
theme: 'dark',
theme: "dark",
},
},
};
it('should get a nested value when the path is valid', () => {
const result = getNestedValue(data, 'user.profile.name');
expect(result).toBe('Alice');
it("should get a nested value when the path is valid", () => {
const result = getNestedValue(data, "user.profile.name");
expect(result).toBe("Alice");
});
it('should return undefined for non-existent property', () => {
const result = getNestedValue(data, 'user.profile.gender');
it("should return undefined for non-existent property", () => {
const result = getNestedValue(data, "user.profile.gender");
expect(result).toBeUndefined();
});
it('should return undefined when accessing a non-existent deep path', () => {
const result = getNestedValue(data, 'user.nonexistent.field');
it("should return undefined when accessing a non-existent deep path", () => {
const result = getNestedValue(data, "user.nonexistent.field");
expect(result).toBeUndefined();
});
it('should return undefined if a middle level is undefined', () => {
const result = getNestedValue({ user: undefined }, 'user.profile.name');
it("should return undefined if a middle level is undefined", () => {
const result = getNestedValue({ user: undefined }, "user.profile.name");
expect(result).toBeUndefined();
});
it('should return the correct value for a nested setting', () => {
const result = getNestedValue(data, 'user.settings.theme');
expect(result).toBe('dark');
it("should return the correct value for a nested setting", () => {
const result = getNestedValue(data, "user.settings.theme");
expect(result).toBe("dark");
});
it('should work for a single-level path', () => {
const result = getNestedValue({ a: 1, b: 2 }, 'b');
it("should work for a single-level path", () => {
const result = getNestedValue({ a: 1, b: 2 }, "b");
expect(result).toBe(2);
});
it('should return the entire object if path is empty', () => {
expect(() => getNestedValue(data, '')()).toThrow();
it("should return the entire object if path is empty", () => {
expect(() => getNestedValue(data, "")()).toThrow();
});
it('should handle paths with array indexes', () => {
const complexData = { list: [{ name: 'Item1' }, { name: 'Item2' }] };
const result = getNestedValue(complexData, 'list.1.name');
expect(result).toBe('Item2');
it("should handle paths with array indexes", () => {
const complexData = { list: [{ name: "Item1" }, { name: "Item2" }] };
const result = getNestedValue(complexData, "list.1.name");
expect(result).toBe("Item2");
});
it('should return undefined when accessing an out-of-bounds array index', () => {
const complexData = { list: [{ name: 'Item1' }] };
const result = getNestedValue(complexData, 'list.2.name');
it("should return undefined when accessing an out-of-bounds array index", () => {
const complexData = { list: [{ name: "Item1" }] };
const result = getNestedValue(complexData, "list.2.name");
expect(result).toBeUndefined();
});
});
@@ -1,8 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { openWindow } from '../window';
import { openWindow } from "../window";
describe('openWindow', () => {
describe("openWindow", () => {
// 保存原始的 window.open 函数
let originalOpen: typeof window.open;
@@ -14,9 +14,9 @@ describe('openWindow', () => {
window.open = originalOpen;
});
it('should call window.open with correct arguments', () => {
const url = 'https://example.com';
const options = { noopener: true, noreferrer: true, target: '_blank' };
it("should call window.open with correct arguments", () => {
const url = "https://example.com";
const options = { noopener: true, noreferrer: true, target: "_blank" };
window.open = vi.fn();
@@ -24,10 +24,6 @@ describe('openWindow', () => {
openWindow(url, options);
// 验证 window.open 是否被正确地调用
expect(window.open).toHaveBeenCalledWith(
url,
options.target,
'noopener=yes,noreferrer=yes',
);
expect(window.open).toHaveBeenCalledWith(url, options.target, "noopener=yes,noreferrer=yes");
});
});
@@ -72,7 +72,7 @@ function diff<T extends Record<string, any>>(obj1: T, obj2: T): DiffResult<T> {
const diffResult: any = {};
const keys = new Set([...Object.keys(o1), ...Object.keys(o2)]);
keys.forEach((key) => {
keys.forEach(key => {
const valueDiff = findDifferences(o1[key], o2[key]);
if (valueDiff !== undefined) {
diffResult[key] = valueDiff;
@@ -19,7 +19,7 @@ export function getElementVisibleRect(element?: HTMLElement | null | undefined):
left: 0,
right: 0,
top: 0,
width: 0
width: 0,
};
}
const rect = element.getBoundingClientRect();
@@ -39,7 +39,7 @@ export function getElementVisibleRect(element?: HTMLElement | null | undefined):
left,
right,
top,
width: Math.max(0, right - left)
width: Math.max(0, right - left),
};
}
@@ -17,7 +17,7 @@ async function loadNprogress() {
nProgressInstance = await import("nprogress");
nProgressInstance.configure({
showSpinner: true,
speed: 300
speed: 300,
});
return nProgressInstance;
}
@@ -3,10 +3,7 @@
* @param {object=} errorExt - Additional Information you can pass to the err object
* @return { Promise }
*/
export async function to<T, U = Error>(
promise: Readonly<Promise<T>>,
errorExt?: object,
): Promise<[null, T] | [U, undefined]> {
export async function to<T, U = Error>(promise: Readonly<Promise<T>>, errorExt?: object): Promise<[null, T] | [U, undefined]> {
try {
const data = await promise;
const result: [null, T] = [null, data];
@@ -13,7 +13,7 @@ interface TreeConfigOptions {
function traverseTreeValues<T, V>(tree: T[], getValue: (node: T) => V, options?: TreeConfigOptions): V[] {
const result: V[] = [];
const { childProps } = options || {
childProps: "children"
childProps: "children",
};
const dfs = (treeNode: T) => {
@@ -45,7 +45,7 @@ function traverseTreeValues<T, V>(tree: T[], getValue: (node: T) => V, options?:
*/
function filterTree<T extends Record<string, any>>(tree: T[], filter: (node: T) => boolean, options?: TreeConfigOptions): T[] {
const { childProps } = options || {
childProps: "children"
childProps: "children",
};
const _filterTree = (nodes: T[]): T[] => {
@@ -71,9 +71,9 @@ function filterTree<T extends Record<string, any>>(tree: T[], filter: (node: T)
*/
function mapTree<T, V extends Record<string, any>>(tree: T[], mapper: (node: T) => V, options?: TreeConfigOptions): V[] {
const { childProps } = options || {
childProps: "children"
childProps: "children",
};
return tree.map((node) => {
return tree.map(node => {
const mapperNode: Record<string, any> = mapper(node);
if (mapperNode[childProps]) {
mapperNode[childProps] = mapTree(mapperNode[childProps], mapper, options);
@@ -6,7 +6,7 @@
*/
function uniqueByField<T>(arr: T[], key: keyof T): T[] {
const seen = new Map<any, T>();
return arr.filter((item) => {
return arr.filter(item => {
const value = item[key];
return seen.has(value) ? false : (seen.set(value, item), true);
});
@@ -2,7 +2,7 @@ export function bindMethods<T extends object>(instance: T): void {
const prototype = Object.getPrototypeOf(instance);
const propertyNames = Object.getOwnPropertyNames(prototype);
propertyNames.forEach((propertyName) => {
propertyNames.forEach(propertyName => {
const descriptor = Object.getOwnPropertyDescriptor(prototype, propertyName);
const propertyValue = instance[propertyName as keyof T];