add DNS service test

This commit is contained in:
Kfir Dayan 2024-01-21 11:56:08 +02:00
parent 23bdef3fbc
commit af903ef430
2 changed files with 18 additions and 2 deletions

View file

@ -1,8 +1,14 @@
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from '@nestjs/testing';
import { DnsService } from './dns.service'; import { DnsService } from './dns.service';
import * as dns from 'dns';
jest.mock('dns', () => ({
lookup: jest.fn(),
}));
describe('DnsService', () => { describe('DnsService', () => {
let service: DnsService; let service: DnsService;
let dnsLookupMock: jest.Mock;
beforeEach(async () => { beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({ const module: TestingModule = await Test.createTestingModule({
@ -10,9 +16,20 @@ describe('DnsService', () => {
}).compile(); }).compile();
service = module.get<DnsService>(DnsService); service = module.get<DnsService>(DnsService);
dnsLookupMock = (dns.lookup as unknown) as jest.Mock;
}); });
it('should be defined', () => { it('should be defined', () => {
expect(service).toBeDefined(); expect(service).toBeDefined();
}); });
});
it('should return true for a valid URL', async () => {
dnsLookupMock.mockImplementation((hostname, callback) => callback(null, '1.1.1.1'));
expect(await service.isValidUrl('http://example.com')).toBe(true);
});
it('should return false for an invalid URL', async () => {
dnsLookupMock.mockImplementation((hostname, callback) => callback(new Error('not found'), null));
expect(await service.isValidUrl('http://invalid-url.com')).toBe(false);
});
});

View file

@ -7,7 +7,6 @@ export class DnsService {
private lookup = util.promisify(dns.lookup); private lookup = util.promisify(dns.lookup);
async isValidUrl(url: string): Promise<boolean> { async isValidUrl(url: string): Promise<boolean> {
console.log(url)
try { try {
const hostname = new URL(url).hostname; const hostname = new URL(url).hostname;
await this.lookup(hostname); await this.lookup(hostname);