diff --git a/web/packages/teleterm/src/services/grpcCredentials/files.test.ts b/web/packages/teleterm/src/services/grpcCredentials/files.test.ts index 26078b02ee54a..385dfbd33f780 100644 --- a/web/packages/teleterm/src/services/grpcCredentials/files.test.ts +++ b/web/packages/teleterm/src/services/grpcCredentials/files.test.ts @@ -36,6 +36,10 @@ afterAll(async () => { await fs.rm(tempDir, { recursive: true, force: true }); }); +beforeEach(() => { + jest.restoreAllMocks(); +}); + describe('readGrpcCert', () => { it('reads the file if the file already exists', async () => { await fs.writeFile(path.join(tempDir, 'already-exists'), 'foobar'); @@ -64,4 +68,17 @@ describe('readGrpcCert', () => { message: expect.stringContaining('within the timeout'), }); }); + + it('returns an error if stat fails', async () => { + const expectedError = new Error('Something went wrong'); + jest.spyOn(fs, 'stat').mockRejectedValue(expectedError); + + await expect( + readGrpcCert( + tempDir, + 'non-existent', + { timeoutMs: 100 } // Make sure that the test doesn't hang for 10s on failure. + ) + ).rejects.toEqual(expectedError); + }); }); diff --git a/web/packages/teleterm/src/services/grpcCredentials/files.ts b/web/packages/teleterm/src/services/grpcCredentials/files.ts index e20c71f898f95..c8eaac1cffec4 100644 --- a/web/packages/teleterm/src/services/grpcCredentials/files.ts +++ b/web/packages/teleterm/src/services/grpcCredentials/files.ts @@ -17,7 +17,7 @@ */ import path from 'path'; -import { watch } from 'fs'; +import { type Stats, watch } from 'fs'; import { readFile, writeFile, stat, rename } from 'fs/promises'; import { wait } from 'shared/utils/wait'; @@ -64,7 +64,17 @@ export async function readGrpcCert( const abortController = new AbortController(); async function fileExistsAndHasSize(): Promise { - return !!(await stat(fullPath)).size; + let stats: Stats; + try { + stats = await stat(fullPath); + } catch (error) { + if (error?.code === 'ENOENT') { + return false; + } + throw error; + } + + return !!stats.size; } function waitForFile(): Promise { @@ -94,7 +104,7 @@ export async function readGrpcCert( fileExistsAndHasSize().then( exists => exists && resolve(readFile(fullPath)), - () => {} // Ignore err. + err => reject(err) ); }); }