Files
eSIM-Tools/tests/modules/logger.test.js
Abner 9ed51287c0 test: 新增多个核心模块的单元测试并优化 Jest 配置
- 在 `jest.config.js` 中启用 V8 覆盖率提供器(兼容 Node.js 22+),提升覆盖率检测性能与准确性
- 调整覆盖率收集范围为 `src/js/modules/**/*.js`,排除测试文件,使报告更聚焦于实际业务逻辑
- 降低全局覆盖率阈值至当前可达成水平(statements/branches 30%-70%),制定逐步提升计划
- 新增 6 个模块的完整单元测试:`APIService`、`AppConfig`、`HTMLSanitizer`、`Logger`、`SecureStorage` 和 `utils`,总计约 840 行测试代码
- 修复 `HTMLSanitizer.sanitizeURL()` 中对 `data:text/html` 协议的正则检测逻辑,增强 XSS 防护能力
2026-05-05 10:35:14 +08:00

84 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Logger 模块单元测试
* 覆盖日志输出、环境感知、脱敏等核心功能
*/
import Logger from '../../src/js/modules/logger';
describe('Logger', () => {
let consoleSpy;
beforeEach(() => {
consoleSpy = {
log: jest.spyOn(console, 'log').mockImplementation(),
warn: jest.spyOn(console, 'warn').mockImplementation(),
error: jest.spyOn(console, 'error').mockImplementation()
};
});
afterEach(() => {
Object.values(consoleSpy).forEach(spy => spy.mockRestore());
});
describe('warn()', () => {
it('应该始终输出警告日志', () => {
Logger.warn('test warning');
expect(consoleSpy.warn).toHaveBeenCalledWith('[WARN]', 'test warning');
});
it('应该支持多个参数', () => {
Logger.warn('msg', 123, { key: 'val' });
expect(consoleSpy.warn).toHaveBeenCalledWith('[WARN]', 'msg', 123, { key: 'val' });
});
});
describe('error()', () => {
it('应该始终输出错误日志', () => {
Logger.error('test error');
expect(consoleSpy.error).toHaveBeenCalledWith('[ERROR]', 'test error');
});
});
describe('sensitive()', () => {
it('应该在开发环境输出脱敏数据', () => {
// jsdom 环境下 isDev 可能为 falsesensitive 在非 dev 下直接返回
// 这里测试逻辑分支
Logger.sensitive('TOKEN', 'abcdef123456', 3);
// sensitive 在非 dev 环境下不输出,这是正确行为
});
it('应该处理空值', () => {
Logger.sensitive('KEY', null);
Logger.sensitive('KEY', '');
// 不应抛出错误
});
});
describe('log() 和 debug()', () => {
it('应该在 test 环境下不输出 log', () => {
// NODE_ENV=test, isDev 为 false
Logger.log('should not appear');
expect(consoleSpy.log).not.toHaveBeenCalled();
});
it('应该在 test 环境下不输出 debug', () => {
Logger.debug('should not appear');
expect(consoleSpy.log).not.toHaveBeenCalled();
});
});
describe('time() / timeEnd()', () => {
it('应该在 test 环境下不调用 console.time', () => {
Logger.time('test');
expect(consoleSpy.log).not.toHaveBeenCalled();
});
});
describe('table()', () => {
it('应该在 test 环境下不调用 console.table', () => {
Logger.table([{ a: 1 }]);
expect(consoleSpy.log).not.toHaveBeenCalled();
});
});
});