2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2024-04-10 02:43:44 +00:00
|
|
|
// This module is browser compatible.
|
2024-05-17 05:32:03 +00:00
|
|
|
import { buildMessage, diff, diffStr, format, red } from "@std/internal";
|
2023-07-13 07:04:30 +00:00
|
|
|
import { AssertionError } from "./assertion_error.ts";
|
|
|
|
|
|
|
|
/**
|
2024-05-15 03:46:11 +00:00
|
|
|
* Make an assertion that `actual` and `expected` are equal using
|
|
|
|
* {@linkcode Object.is} for equality comparison. If not, then throw.
|
2023-07-13 07:04:30 +00:00
|
|
|
*
|
2024-05-30 02:38:16 +00:00
|
|
|
* @example Usage
|
|
|
|
* ```ts no-eval
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { assertStrictEquals } from "@std/assert/assert-strict-equals";
|
2023-07-13 07:04:30 +00:00
|
|
|
*
|
2023-12-06 17:13:38 +00:00
|
|
|
* const a = {};
|
|
|
|
* const b = a;
|
|
|
|
* assertStrictEquals(a, b); // Doesn't throw
|
2023-07-13 07:04:30 +00:00
|
|
|
*
|
2023-12-06 17:13:38 +00:00
|
|
|
* const c = {};
|
|
|
|
* const d = {};
|
|
|
|
* assertStrictEquals(c, d); // Throws
|
2023-07-13 07:04:30 +00:00
|
|
|
* ```
|
2024-05-30 02:38:16 +00:00
|
|
|
*
|
|
|
|
* @typeParam T The type of the expected value.
|
|
|
|
* @param actual The actual value to compare.
|
|
|
|
* @param expected The expected value to compare.
|
|
|
|
* @param msg The optional message to display if the assertion fails.
|
2023-07-13 07:04:30 +00:00
|
|
|
*/
|
|
|
|
export function assertStrictEquals<T>(
|
|
|
|
actual: unknown,
|
|
|
|
expected: T,
|
|
|
|
msg?: string,
|
|
|
|
): asserts actual is T {
|
2024-05-13 07:50:51 +00:00
|
|
|
if (Object.is(actual, expected)) {
|
2023-07-13 07:04:30 +00:00
|
|
|
return;
|
|
|
|
}
|
2024-05-13 07:50:51 +00:00
|
|
|
|
2023-07-13 07:04:30 +00:00
|
|
|
const msgSuffix = msg ? `: ${msg}` : ".";
|
|
|
|
let message: string;
|
|
|
|
|
|
|
|
const actualString = format(actual);
|
|
|
|
const expectedString = format(expected);
|
|
|
|
|
|
|
|
if (actualString === expectedString) {
|
|
|
|
const withOffset = actualString
|
|
|
|
.split("\n")
|
|
|
|
.map((l) => ` ${l}`)
|
|
|
|
.join("\n");
|
|
|
|
message =
|
|
|
|
`Values have the same structure but are not reference-equal${msgSuffix}\n\n${
|
|
|
|
red(withOffset)
|
|
|
|
}\n`;
|
|
|
|
} else {
|
2024-05-09 06:39:21 +00:00
|
|
|
const stringDiff = (typeof actual === "string") &&
|
|
|
|
(typeof expected === "string");
|
|
|
|
const diffResult = stringDiff
|
2024-05-17 05:32:03 +00:00
|
|
|
? diffStr(actual as string, expected as string)
|
2024-05-09 06:39:21 +00:00
|
|
|
: diff(actualString.split("\n"), expectedString.split("\n"));
|
|
|
|
const diffMsg = buildMessage(diffResult, { stringDiff }).join("\n");
|
|
|
|
message = `Values are not strictly equal${msgSuffix}\n${diffMsg}`;
|
2023-07-13 07:04:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
throw new AssertionError(message);
|
|
|
|
}
|