Skip to content

Commit 01bc144

Browse files
committed
added common util tests
1 parent 80f6a09 commit 01bc144

File tree

2 files changed

+56
-11
lines changed

2 files changed

+56
-11
lines changed

src/utils/common.spec.ts

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
* Public License, v. 2.0 that can be found in the LICENSE file.
66
*/
77

8-
import { describe, expect, it } from 'vitest';
9-
import { capitalize, groupBy, randInt, splitAt, toHex } from '.';
8+
import { describe, expect, it, vi } from 'vitest';
9+
import { assert, capitalize, debounce, groupBy, isClass, randInt, sleep, splitAt, toHex, uid } from '.';
1010

1111
describe('The common utils', () => {
1212
it.each([
@@ -83,4 +83,58 @@ describe('The common utils', () => {
8383
expect(randInt(1, 5)).toBeLessThanOrEqual(5);
8484
}
8585
});
86+
87+
it('should assert a condition (assert)', () => {
88+
expect(() => assert(1)).not.toThrowError();
89+
expect(() => assert(0)).toThrowError();
90+
});
91+
92+
it('should debounce a method (debunce)', async () => {
93+
const fn = vi.fn();
94+
95+
const debouncedFn = debounce(() => fn(performance.now()), 10);
96+
97+
debouncedFn();
98+
debouncedFn();
99+
100+
await sleep(20);
101+
102+
expect(fn).toBeCalledTimes(1);
103+
104+
debouncedFn();
105+
await sleep(11);
106+
debouncedFn();
107+
108+
await sleep(20);
109+
110+
expect(fn).toBeCalledTimes(3);
111+
112+
expect(fn.mock.calls[0][0]).toBeTypeOf('number');
113+
});
114+
115+
it('should be able to detect classes (isClass)', () => {
116+
expect(isClass(5)).toBe(false);
117+
expect(isClass(() => false)).toBe(false);
118+
expect(isClass('')).toBe(false);
119+
expect(isClass(new class { }())).toBe(false);
120+
expect(isClass(class { })).toBe(true);
121+
});
122+
123+
it('should be able to capitalize strings (capitalize)', () => {
124+
expect(capitalize('hello World')).toBe('Hello World');
125+
});
126+
127+
it('should be able to generate short uids (uid)', () => {
128+
expect(uid()).toBeTypeOf('string');
129+
expect(uid()?.length).toBe(8);
130+
expect(uid()).not.toBe(uid());
131+
});
132+
133+
it('should not sleep if the number is less than 0 (sleep)', async () => {
134+
const now = performance.now();
135+
136+
await sleep(-10);
137+
138+
expect(performance.now() -now).toBeLessThan(1);
139+
});
86140
});

src/utils/common.ts

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -93,15 +93,6 @@ export function arraymove(arr: any[], fromIndex: number, toIndex: number) {
9393
arr.splice(toIndex, 0, element);
9494
}
9595

96-
/**
97-
* Timer that rejects after n seconds
98-
*/
99-
export async function rejectIn(seconds: number) {
100-
await new Promise((_resolve, reject: any) =>
101-
setTimeout(() => reject('took too long'), seconds * 1000),
102-
);
103-
}
104-
10596
/**
10697
* Short unique id (not as secure as uuid 4 though)
10798
*/

0 commit comments

Comments
 (0)