Add unit tests for utils and module pure functions

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-05 19:14:13 +08:00
parent e596bcd18e
commit 83c2db7582
8 changed files with 563 additions and 0 deletions

View File

@@ -0,0 +1,72 @@
import { describe, it, expect, beforeEach } from 'vitest';
import {
getCookie,
setCookie,
setCookieWithoutExpiration,
deleteCookie,
} from '@/utils/cookieUtil.js';
describe('cookieUtil', () => {
beforeEach(() => {
// Clear all cookies before each test
document.cookie.split(';').forEach((c) => {
const name = c.split('=')[0].trim();
if (name) {
document.cookie =
name + '=; Max-Age=-99999999; path=/';
}
});
});
describe('getCookie', () => {
it('returns null when cookie does not exist', () => {
expect(getCookie('nonexistent')).toBeNull();
});
it('returns value of an existing cookie', () => {
document.cookie = 'testKey=testValue';
expect(getCookie('testKey')).toBe('testValue');
});
it('returns correct value when multiple cookies exist',
() => {
document.cookie = 'first=aaa';
document.cookie = 'second=bbb';
document.cookie = 'third=ccc';
expect(getCookie('second')).toBe('bbb');
});
it('does not match partial cookie names', () => {
document.cookie = 'testKey=value';
expect(getCookie('test')).toBeNull();
});
});
describe('setCookie', () => {
it('sets a cookie with default 1-day expiration', () => {
setCookie('myKey', 'myValue');
expect(getCookie('myKey')).toBe('myValue');
});
it('sets a cookie with empty value', () => {
setCookie('emptyKey', '');
expect(getCookie('emptyKey')).toBe('');
});
});
describe('setCookieWithoutExpiration', () => {
it('sets a session cookie', () => {
setCookieWithoutExpiration('sessionKey', 'sessionVal');
expect(getCookie('sessionKey')).toBe('sessionVal');
});
});
describe('deleteCookie', () => {
it('removes an existing cookie', () => {
setCookie('toDelete', 'value');
expect(getCookie('toDelete')).toBe('value');
deleteCookie('toDelete');
expect(getCookie('toDelete')).toBeNull();
});
});
});