UNPKG

dts-jest

Version:

A preprocessor for Jest to snapshot test TypeScript declaration (.d.ts) files

68 lines (67 loc) 3.11 kB
"use strict"; exports.__esModule = true; var definitions_1 = require("../definitions"); var create_message_1 = require("./create-message"); var get_diagnostic_message_1 = require("./get-diagnostic-message"); var get_display_line_1 = require("./get-display-line"); var get_trigger_line_1 = require("./get-trigger-line"); var traverse_node_1 = require("./traverse-node"); exports.create_snapshots = function (filename, triggers, normalized_config) { var ts = normalized_config.typescript, compiler_options = normalized_config.compiler_options, file_names = normalized_config.file_names, enclosing_declaration = normalized_config.enclosing_declaration, type_format_flags = normalized_config.type_format_flags; var program = ts.createProgram([filename].concat(file_names), compiler_options); var source_file = program.getSourceFile(filename); var body_line_map = new Map(); triggers.forEach(function (trigger) { if (trigger.header.flags & definitions_1.TriggerHeaderFlags.Assertion) { var body_line = get_trigger_line_1.get_trigger_body_line(trigger.header.line); body_line_map.set(body_line, trigger); } }); var unmatched_diagnostics = []; var snapshots = []; var diagnostics = ts.getPreEmitDiagnostics(program, source_file); for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { var diagnostic = diagnostics_1[_i]; var position = diagnostic.start; var line = source_file.getLineAndCharacterOfPosition(position).line; if (!body_line_map.has(line)) { unmatched_diagnostics.push({ line: line, message: get_diagnostic_message_1.get_diagnostic_message(diagnostic) }); continue; } snapshots.push({ line: line, diagnostic: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n') }); body_line_map["delete"](line); } if (unmatched_diagnostics.length !== 0) { throw new Error(create_message_1.create_message('Unmatched diagnostic(s) detected:', unmatched_diagnostics.map(function (_a) { var line = _a.line, message = _a.message; return source_file.fileName + ":" + get_display_line_1.get_display_line(line) + " " + message; }))); } if (body_line_map.size === 0) { return snapshots; } var checker = program.getTypeChecker(); traverse_node_1.traverse_node(source_file, function (node) { var position = node.getStart(); var line = source_file.getLineAndCharacterOfPosition(position).line; if (!body_line_map.has(line)) { return; } var target_node = node.getChildAt(0); var type = checker.getTypeAtLocation(target_node); snapshots.push({ line: line, inference: checker.typeToString(type, // istanbul ignore next enclosing_declaration ? node : undefined, type_format_flags) }); body_line_map["delete"](line); }, ts); return snapshots; };