|
| 1 | +import { getuserAgentSuffix } from './cosmos-db.utils'; |
| 2 | +import { readFile } from 'fs/promises'; |
| 3 | +import { join } from 'path'; |
| 4 | + |
| 5 | +// Mock fs/promises |
| 6 | +jest.mock('fs/promises'); |
| 7 | +const mockReadFile = readFile as jest.MockedFunction<typeof readFile>; |
| 8 | + |
| 9 | +describe('cosmos-db.utils', () => { |
| 10 | + describe('getuserAgentSuffix', () => { |
| 11 | + beforeEach(() => { |
| 12 | + jest.clearAllMocks(); |
| 13 | + }); |
| 14 | + |
| 15 | + it('should return user agent with package info when package.json exists', async () => { |
| 16 | + const mockPackageJson = { |
| 17 | + name: '@nestjs/azure-database', |
| 18 | + version: '4.0.0', |
| 19 | + }; |
| 20 | + |
| 21 | + mockReadFile.mockResolvedValue(JSON.stringify(mockPackageJson)); |
| 22 | + |
| 23 | + const result = await getuserAgentSuffix(); |
| 24 | + |
| 25 | + expect(mockReadFile).toHaveBeenCalledWith(join(__dirname, '..', '..', 'package.json'), 'utf8'); |
| 26 | + expect(result).toBe( |
| 27 | + `node.js/${process.version} (${process.platform}; ${process.arch}) ${mockPackageJson.name}/${mockPackageJson.version}`, |
| 28 | + ); |
| 29 | + }); |
| 30 | + |
| 31 | + it('should return fallback user agent when package.json cannot be read', async () => { |
| 32 | + mockReadFile.mockRejectedValue(new Error('ENOENT: no such file or directory')); |
| 33 | + |
| 34 | + const result = await getuserAgentSuffix(); |
| 35 | + |
| 36 | + expect(mockReadFile).toHaveBeenCalledWith(join(__dirname, '..', '..', 'package.json'), 'utf8'); |
| 37 | + expect(result).toBe(`node.js/${process.version} (${process.platform}; ${process.arch}) @nestjs/azure-database/0.0.0`); |
| 38 | + }); |
| 39 | + |
| 40 | + it('should return fallback user agent when package.json is invalid JSON', async () => { |
| 41 | + mockReadFile.mockResolvedValue('invalid json content'); |
| 42 | + |
| 43 | + const result = await getuserAgentSuffix(); |
| 44 | + |
| 45 | + expect(mockReadFile).toHaveBeenCalledWith(join(__dirname, '..', '..', 'package.json'), 'utf8'); |
| 46 | + expect(result).toBe(`node.js/${process.version} (${process.platform}; ${process.arch}) @nestjs/azure-database/0.0.0`); |
| 47 | + }); |
| 48 | + |
| 49 | + it('should return fallback user agent when package.json has missing properties', async () => { |
| 50 | + const mockPackageJson = { |
| 51 | + name: '@nestjs/azure-database', |
| 52 | + // version is missing |
| 53 | + }; |
| 54 | + |
| 55 | + mockReadFile.mockResolvedValue(JSON.stringify(mockPackageJson)); |
| 56 | + |
| 57 | + const result = await getuserAgentSuffix(); |
| 58 | + |
| 59 | + expect(result).toBe(`node.js/${process.version} (${process.platform}; ${process.arch}) @nestjs/azure-database/0.0.0`); |
| 60 | + }); |
| 61 | + }); |
| 62 | +}); |
0 commit comments