feat: add unit test

This commit is contained in:
Mohamed Marrouchi 2025-01-23 16:36:41 +01:00
parent 2694a4f802
commit 395b033f74
2 changed files with 65 additions and 3 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
@ -143,4 +143,61 @@ describe('SettingService', () => {
});
});
});
describe('getAllowedOrigins', () => {
it('should return a set of unique origins from allowed_domains settings', async () => {
const mockSettings = [
{
label: 'allowed_domains',
value: 'https://example.com,https://test.com',
},
{
label: 'allowed_domains',
value: 'https://example.com,https://another.com',
},
] as Setting[];
jest.spyOn(settingService, 'find').mockResolvedValue(mockSettings);
const result = await settingService.getAllowedOrigins();
expect(settingService.find).toHaveBeenCalledWith({
label: 'allowed_domains',
});
expect(result).toEqual(
new Set([
'https://example.com',
'https://test.com',
'https://another.com',
]),
);
});
it('should return an empty set if no settings are found', async () => {
jest.spyOn(settingService, 'find').mockResolvedValue([]);
const result = await settingService.getAllowedOrigins();
expect(settingService.find).toHaveBeenCalledWith({
label: 'allowed_domains',
});
expect(result).toEqual(new Set());
});
it('should handle settings with empty values', async () => {
const mockSettings = [
{ label: 'allowed_domains', value: '' },
{ label: 'allowed_domains', value: 'https://example.com' },
] as Setting[];
jest.spyOn(settingService, 'find').mockResolvedValue(mockSettings);
const result = await settingService.getAllowedOrigins();
expect(settingService.find).toHaveBeenCalledWith({
label: 'allowed_domains',
});
expect(result).toEqual(new Set(['https://example.com']));
});
});
});

View File

@ -24,6 +24,7 @@ import { BaseService } from '@/utils/generics/base-service';
import { SettingCreateDto } from '../dto/setting.dto';
import { SettingRepository } from '../repositories/setting.repository';
import { Setting } from '../schemas/setting.schema';
import { TextSetting } from '../schemas/types';
import { SettingSeeder } from '../seeds/setting.seed';
@Injectable()
@ -137,10 +138,14 @@ export class SettingService extends BaseService<Setting> {
*/
@Cacheable(ALLOWED_ORIGINS_CACHE_KEY)
async getAllowedOrigins() {
const settings = await this.find({ label: 'allowed_domains' });
const settings = (await this.find({
label: 'allowed_domains',
})) as TextSetting[];
const uniqueOrigins = new Set(
settings.flatMap((setting) => setting.value.split(',')),
settings.flatMap((setting) =>
setting.value.split(',').filter((o) => !!o),
),
);
return uniqueOrigins;