diff --git a/src/__tests__/utils.spec.ts b/src/__tests__/utils.spec.ts index 72addaf..7b3ba34 100644 --- a/src/__tests__/utils.spec.ts +++ b/src/__tests__/utils.spec.ts @@ -26,6 +26,7 @@ import { isFalse, getAttachments, isErrorLog, + fileExists, calculateRpStatus, } from '../utils'; import fs from 'fs'; @@ -56,6 +57,23 @@ describe('testing utils', () => { }); }); + describe('fileExists', () => { + test('should return true', async () => { + jest.spyOn(fs.promises, 'stat').mockImplementationOnce(() => Promise.resolve({} as fs.Stats)); + + const existingFilePath = 'existing-file-path'; + const isFileExist = await fileExists(existingFilePath); + + expect(isFileExist).toBe(true); + }); + test('should return false', async () => { + const notExistingFilePath = 'not-existing-file-path'; + const isFileExist = await fileExists(notExistingFilePath); + + expect(isFileExist).toBe(false); + }); + }); + describe('promiseErrorHandler', () => { let spyConsoleError: jest.SpyInstance; beforeEach(() => { @@ -242,7 +260,7 @@ describe('testing utils', () => { const file1Data = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); const file2Data = Buffer.from([1, 2, 3, 4, 5, 6, 7]); - jest.spyOn(fs, 'existsSync').mockImplementationOnce((): boolean => true); + jest.spyOn(fs.promises, 'stat').mockImplementationOnce(() => Promise.resolve({} as fs.Stats)); jest.spyOn(fs.promises, 'readFile').mockImplementationOnce(async () => file1Data); diff --git a/src/utils.ts b/src/utils.ts index 1a29c85..c80acc5 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -92,6 +92,20 @@ export const sendEventToReporter = (type: string, data: any, suite?: string): vo process.stdout.write(JSON.stringify({ type, data, suite })); }; +export const fileExists = async (filePath: string) => { + try { + await fsPromises.stat(filePath); + return true; + } catch (error) { + // ENOENT code - File does not exist + if (error.code === 'ENOENT') { + return false; + } else { + throw error; + } + } +}; + export const getAttachments = async ( attachments: TestResult['attachments'], { uploadTrace, uploadVideo }: AttachmentsConfig = { uploadTrace: true, uploadVideo: true }, @@ -122,7 +136,8 @@ export const getAttachments = async ( if (body) { fileContent = body; } else { - if (!fs.existsSync(attachmentPath)) { + const isFileExist = await fileExists(attachmentPath); + if (!isFileExist) { return; } fileContent = await fsPromises.readFile(attachmentPath);