|
| 1 | +import * as fs from 'fs'; |
| 2 | +import * as path from 'path'; |
| 3 | + |
| 4 | +import { Test, TestingModule } from '@nestjs/testing'; |
| 5 | + |
| 6 | +import { GraphQLLoaderService } from './graphql-loader.service'; |
| 7 | + |
| 8 | +jest.mock('fs'); |
| 9 | +jest.mock('path'); |
| 10 | + |
| 11 | +describe('GraphQLLoaderService', () => { |
| 12 | + let service: GraphQLLoaderService; |
| 13 | + |
| 14 | + const mockFilePath = 'queries/test.graphql'; |
| 15 | + const mockFullPath = '/app/queries/test.graphql'; |
| 16 | + const mockQuery = 'query Test { test }'; |
| 17 | + const mockedReadFileSync = fs.readFileSync as jest.MockedFunction< |
| 18 | + typeof fs.readFileSync |
| 19 | + >; |
| 20 | + |
| 21 | + beforeEach(async () => { |
| 22 | + jest.clearAllMocks(); |
| 23 | + |
| 24 | + (path.join as jest.Mock).mockReturnValue(mockFullPath); |
| 25 | + |
| 26 | + const module: TestingModule = await Test.createTestingModule({ |
| 27 | + providers: [GraphQLLoaderService], |
| 28 | + }).compile(); |
| 29 | + |
| 30 | + service = module.get<GraphQLLoaderService>(GraphQLLoaderService); |
| 31 | + }); |
| 32 | + |
| 33 | + it('should be defined', () => { |
| 34 | + expect(service).toBeDefined(); |
| 35 | + }); |
| 36 | + |
| 37 | + it('should load query from file when cache is empty', () => { |
| 38 | + mockedReadFileSync.mockReturnValue(mockQuery as string); |
| 39 | + |
| 40 | + const result = service.loadQuery(mockFilePath); |
| 41 | + |
| 42 | + expect(result).toBe(mockQuery); |
| 43 | + expect(fs.readFileSync).toHaveBeenCalledWith(mockFullPath, 'utf-8'); |
| 44 | + }); |
| 45 | + |
| 46 | + it('should cache the query after loading from file', () => { |
| 47 | + mockedReadFileSync.mockReturnValue(mockQuery as string); |
| 48 | + |
| 49 | + service.loadQuery(mockFilePath); |
| 50 | + mockedReadFileSync.mockClear(); |
| 51 | + |
| 52 | + const cachedResult = service.loadQuery(mockFilePath); |
| 53 | + |
| 54 | + expect(cachedResult).toBe(mockQuery); |
| 55 | + expect(mockedReadFileSync).not.toHaveBeenCalled(); |
| 56 | + }); |
| 57 | + |
| 58 | + it('should throw error if file read fails', () => { |
| 59 | + (fs.readFileSync as jest.Mock).mockImplementation(() => { |
| 60 | + throw new Error('File not found'); |
| 61 | + }); |
| 62 | + |
| 63 | + expect(() => service.loadQuery(mockFilePath)).toThrow( |
| 64 | + `Failed to load GraphQL query from ${mockFilePath}: File not found`, |
| 65 | + ); |
| 66 | + }); |
| 67 | + |
| 68 | + it('should clear cache', () => { |
| 69 | + (fs.readFileSync as jest.Mock).mockReturnValue(mockQuery); |
| 70 | + |
| 71 | + service.loadQuery(mockFilePath); |
| 72 | + service.clearCache(); |
| 73 | + |
| 74 | + service.loadQuery(mockFilePath); |
| 75 | + |
| 76 | + expect(fs.readFileSync).toHaveBeenCalledTimes(2); |
| 77 | + }); |
| 78 | +}); |
0 commit comments