refactor: improve assert error by including the failed condition (#34799)

PR Close #34799
This commit is contained in:
Miško Hevery 2019-12-17 11:39:55 -08:00 committed by Matias Niemelä
parent 63c9c2d2be
commit d56cf6a92d
1 changed files with 22 additions and 12 deletions

View File

@ -14,68 +14,78 @@ import {stringify} from './stringify';
export function assertNumber(actual: any, msg: string) {
if (typeof actual != 'number') {
throwError(msg);
throwError(msg, typeof actual, 'number', '===');
}
}
export function assertString(actual: any, msg: string) {
if (typeof actual != 'string') {
throwError(msg, actual === null ? 'null' : typeof actual, 'string', '===');
}
}
export function assertEqual<T>(actual: T, expected: T, msg: string) {
if (actual != expected) {
throwError(msg);
throwError(msg, actual, expected, '==');
}
}
export function assertNotEqual<T>(actual: T, expected: T, msg: string) {
if (actual == expected) {
throwError(msg);
throwError(msg, actual, expected, '!=');
}
}
export function assertSame<T>(actual: T, expected: T, msg: string) {
if (actual !== expected) {
throwError(msg);
throwError(msg, actual, expected, '===');
}
}
export function assertNotSame<T>(actual: T, expected: T, msg: string) {
if (actual === expected) {
throwError(msg);
throwError(msg, actual, expected, '!==');
}
}
export function assertLessThan<T>(actual: T, expected: T, msg: string) {
if (actual >= expected) {
throwError(msg);
throwError(msg, actual, expected, '<');
}
}
export function assertLessThanOrEqual<T>(actual: T, expected: T, msg: string) {
if (actual > expected) {
throwError(msg);
throwError(msg, actual, expected, '<=');
}
}
export function assertGreaterThan<T>(actual: T, expected: T, msg: string) {
if (actual <= expected) {
throwError(msg);
throwError(msg, actual, expected, '>');
}
}
export function assertNotDefined<T>(actual: T, msg: string) {
if (actual != null) {
throwError(msg);
throwError(msg, actual, null, '==');
}
}
export function assertDefined<T>(actual: T, msg: string) {
if (actual == null) {
throwError(msg);
throwError(msg, actual, null, '!=');
}
}
export function throwError(msg: string): never {
export function throwError(msg: string): never;
export function throwError(msg: string, actual: any, expected: any, comparison: string): never;
export function throwError(msg: string, actual?: any, expected?: any, comparison?: string): never {
// tslint:disable-next-line
debugger; // Left intentionally for better debugger experience.
throw new Error(`ASSERTION ERROR: ${msg}`);
throw new Error(
`ASSERTION ERROR: ${msg}` +
(comparison == null ? '' : ` [Expected=> ${expected} ${comparison} ${actual} <=Actual]`));
}
export function assertDomNode(node: any) {