/
loadFile.ts
36 lines (32 loc) · 1.1 KB
/
loadFile.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import path from 'path';
import { InternalError } from './_error';
// Jest seems to throw errors which are not Error Instances.
// To provide better information
// we need to include the original message in the thrown error.
// See https://github.com/toomuchdesign/next-page-tester/issues/269
function seemsJestError(e: unknown): boolean {
return Boolean(e && typeof e === 'object' && 'message' in e);
}
export function loadFile<FileType>({
absolutePath,
}: {
absolutePath: string;
}): FileType {
try {
return require(absolutePath);
} catch (e: unknown) {
const baseName = path.basename(absolutePath);
// @NOTE There are tests covering it but tests coverage seems to not see it
/* istanbul ignore next */
if (e instanceof Error || seemsJestError(e)) {
const error = e as Error;
const internalError = new InternalError(
`Failed to load "${baseName}" file due to ${error.name}: ${error.message}`
);
internalError.stack = error.stack;
throw internalError;
}
/* istanbul ignore next */
throw new InternalError(`Failed to load "${baseName}"`);
}
}