UNPKG

earljs

Version:

Ergonomic, modern and type-safe assertion library

53 lines (52 loc) 1.85 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toThrow = void 0; const ts_essentials_1 = require("ts-essentials"); const format_1 = require("../format"); const isEqual_1 = require("../isEqual"); const matchers_1 = require("../matchers"); function toThrow(control, expected) { (0, ts_essentials_1.assert)(control.actual instanceof Function, 'Actual has to be a function to check if threw'); let actualThrownValue; let threwAnything = false; try { control.actual(); } catch (e) { threwAnything = true; actualThrownValue = e; } // we need special handling for this case otherwise we end up with really dummy error message if (!threwAnything) { return control.assert({ success: false, reason: `Expected to throw but didn't`, negatedReason: '-', }); } const actualFmt = (0, format_1.formatCompact)(actualThrownValue); const expectedFmt = expected instanceof matchers_1.AnythingMatcher ? 'anything' : expected instanceof matchers_1.ErrorMatcher ? expected.format() : (0, format_1.formatCompact)(expected); const reason = `Expected to throw ${expectedFmt} but threw ${actualFmt}`; const negatedReason = `Expected not to throw ${expectedFmt} but threw ${actualFmt}`; if (!(0, isEqual_1.isEqual)(actualThrownValue, expected)) { control.assert({ success: false, reason, negatedReason, actual: (0, format_1.format)(actualThrownValue, null), expected: (0, format_1.format)(expected, actualThrownValue), }); } else { control.assert({ success: true, reason, negatedReason, }); } } exports.toThrow = toThrow;