UNPKG

ts-jest-mock-import-meta

Version:

A simple Typescript AST transformer for ts-jest, that mock import.meta expressions.

65 lines (64 loc) 2.32 kB
import type { TsCompilerInstance } from 'ts-jest'; import ts from 'typescript'; export declare const version = "1.1"; export declare const name = "ts-jest-mock-import-meta"; type ReplacementFunctionContext = { fileName: string; }; type ReplacementFunction = (context: ReplacementFunctionContext) => Record<string, any>; export interface Options extends Record<string, unknown> { readonly metaObjectReplacement: Record<string, any> | ReplacementFunction; } /** * **This transformer is aimed to be used with ts-jest** * * Typescript AST transformer that allow to replace any "import.meta" expressions in typescript files. * import.meta expression is not compatible with jest in commonjs, so it needs to be stripped down * and replaced by a mocked object before transpilation. * * ex (jest.config): * ```` * // ts-jest >= 29.0.0 * transform: { * '^.+\\.tsx?$': [ * 'ts-jest', * { * diagnostics: { * ignoreCodes: [1343] * }, * astTransformers: { * before: [ * { * path: 'node_modules/ts-jest-mock-import-meta', // or, alternatively, 'ts-jest-mock-import-meta' directly, without node_modules. * options: { metaObjectReplacement: { url: 'https://www.url.com' } } * } * ] * } * } * ] * } * // ts-jest < 29.0.0 * globals: { * 'ts-jest': { * diagnostics: { * ignoreCodes: [1343] * }, * astTransformers: { * before: [ * { * path: 'node_modules/ts-jest-mock-import-meta', // or, alternatively, 'ts-jest-mock-import-meta' directly, without * options: { metaObjectReplacement: { url: 'anyValidUrl' } } * } * ] * } * } * } * ```` * IMPORTANT: error code 1343 MUST be ignored. * https://github.com/Microsoft/TypeScript/blob/main/src/compiler/diagnosticMessages.json#L1035 * @param {TsCompilerInstance} [compiler] ts-jest compiler instance. * @param {TransformerOptions} [options] [optional] provide configuration options for the transformer. * @returns {ts.TransformerFactory<ts.SourceFile>} The updated typescript source file */ export declare function factory(compiler: TsCompilerInstance, options?: Options): ts.TransformerFactory<ts.SourceFile>; export {};