From af903ef4308908b83fb60f2a98ee2ce0c3c82c19 Mon Sep 17 00:00:00 2001 From: Kfir Dayan Date: Sun, 21 Jan 2024 11:56:08 +0200 Subject: [PATCH] add DNS service test --- src/dns/dns.service.spec.ts | 19 ++++++++++++++++++- src/dns/dns.service.ts | 1 - 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/dns/dns.service.spec.ts b/src/dns/dns.service.spec.ts index 91db9a2..9126e92 100644 --- a/src/dns/dns.service.spec.ts +++ b/src/dns/dns.service.spec.ts @@ -1,8 +1,14 @@ import { Test, TestingModule } from '@nestjs/testing'; import { DnsService } from './dns.service'; +import * as dns from 'dns'; + +jest.mock('dns', () => ({ + lookup: jest.fn(), +})); describe('DnsService', () => { let service: DnsService; + let dnsLookupMock: jest.Mock; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -10,9 +16,20 @@ describe('DnsService', () => { }).compile(); service = module.get(DnsService); + dnsLookupMock = (dns.lookup as unknown) as jest.Mock; }); it('should be defined', () => { 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); + }); +}); \ No newline at end of file diff --git a/src/dns/dns.service.ts b/src/dns/dns.service.ts index f7cb00d..44f26b3 100644 --- a/src/dns/dns.service.ts +++ b/src/dns/dns.service.ts @@ -7,7 +7,6 @@ export class DnsService { private lookup = util.promisify(dns.lookup); async isValidUrl(url: string): Promise { - console.log(url) try { const hostname = new URL(url).hostname; await this.lookup(hostname);