| 1 |
/** @odoo-module */ |
| 2 |
|
| 3 |
import { markRaw } from "@odoo/owl"; |
| 4 |
import { |
| 5 |
formatXml, |
| 6 |
getActiveElement, |
| 7 |
getNodeAttribute, |
| 8 |
getNodeRect, |
| 9 |
getNodeText, |
| 10 |
getNodeValue, |
| 11 |
getStyle, |
| 12 |
isCheckable, |
| 13 |
isEmpty, |
| 14 |
isNode, |
| 15 |
isNodeDisplayed, |
| 16 |
isNodeVisible, |
| 17 |
queryRect, |
| 18 |
} from "@web/../lib/hoot-dom/helpers/dom"; |
| 19 |
import { |
| 20 |
addInteractionListener, |
| 21 |
getColorHex, |
| 22 |
isFirefox, |
| 23 |
isInstanceOf, |
| 24 |
isIterable, |
| 25 |
R_WHITE_SPACE, |
| 26 |
} from "@web/../lib/hoot-dom/hoot_dom_utils"; |
| 27 |
import { |
| 28 |
CASE_EVENT_TYPES, |
| 29 |
deepCopy, |
| 30 |
deepEqual, |
| 31 |
ElementMap, |
| 32 |
ensureArguments, |
| 33 |
ensureArray, |
| 34 |
formatHumanReadable, |
| 35 |
getConstructor, |
| 36 |
HootError, |
| 37 |
isLabel, |
| 38 |
isNil, |
| 39 |
isOfType, |
| 40 |
makeLabel, |
| 41 |
makeLabelIcon, |
| 42 |
Markup, |
| 43 |
match, |
| 44 |
S_ANY, |
| 45 |
S_NONE, |
| 46 |
strictEqual, |
| 47 |
} from "../hoot_utils"; |
| 48 |
import { mockFetch } from "../mock/network"; |
| 49 |
import { logger } from "./logger"; |
| 50 |
import { Test } from "./test"; |
| 51 |
|
| 52 |
/** |
| 53 |
* @typedef {{ |
| 54 |
* aborted?: boolean; |
| 55 |
* debug?: boolean; |
| 56 |
* }} AfterTestOptions |
| 57 |
* |
| 58 |
* @typedef {import("../hoot_utils").ArgumentType} ArgumentType |
| 59 |
* |
| 60 |
* @typedef {string | ((pass: boolean) => string)} AssertionMessage |
| 61 |
* |
| 62 |
* @typedef {string | string[] | ((pass: boolean, raw: typeof String["raw"]) => string | string[])} AssertionReportMessage |
| 63 |
* |
| 64 |
* @typedef {VerifierOptions & { |
| 65 |
* timeout?: number; |
| 66 |
* }} AsyncVerifierOptions |
| 67 |
* |
| 68 |
* @typedef {InteractionType | "assertion" | "error" | "step"} CaseEventType |
| 69 |
* |
| 70 |
* @typedef {{ exact?: boolean }} ClassListOptions |
| 71 |
* |
| 72 |
* @typedef {{ exact?: boolean; inline?: boolean }} DOMStyleOptions |
| 73 |
* |
| 74 |
* @typedef {{ |
| 75 |
* headless: boolean; |
| 76 |
* }} ExpectBuilderParams |
| 77 |
* |
| 78 |
* @typedef {{ |
| 79 |
* message?: AssertionMessage; |
| 80 |
* not?: boolean; |
| 81 |
* rejects?: boolean; |
| 82 |
* resolves?: boolean; |
| 83 |
* silent?: boolean; |
| 84 |
* }} ExpectOptions |
| 85 |
* |
| 86 |
* @typedef {DeepEqualOptions & { |
| 87 |
* message?: AssertionMessage; |
| 88 |
* }} VerifierOptions |
| 89 |
* |
| 90 |
* @typedef {import("../hoot_utils").DeepEqualOptions} DeepEqualOptions |
| 91 |
* @typedef {import("../hoot_utils").Label} Label |
| 92 |
* |
| 93 |
* @typedef {import("@odoo/hoot-dom").Dimensions} Dimensions |
| 94 |
* @typedef {import("@odoo/hoot-dom").FormatXmlOptions} FormatXmlOptions |
| 95 |
* @typedef {import("@web/../lib/hoot-dom/hoot_dom_utils").InteractionDetails} InteractionDetails |
| 96 |
* @typedef {import("@web/../lib/hoot-dom/hoot_dom_utils").InteractionType} InteractionType |
| 97 |
* @typedef {import("@odoo/hoot-dom").QueryRectOptions} QueryRectOptions |
| 98 |
* @typedef {import("@odoo/hoot-dom").QueryTextOptions} QueryTextOptions |
| 99 |
* @typedef {import("@odoo/hoot-dom").Target} Target |
| 100 |
*/ |
| 101 |
|
| 102 |
/** |
| 103 |
* @template T |
| 104 |
* @typedef {T & ReturnType<Promise.withResolvers> & { |
| 105 |
* options: VerifierOptions; |
| 106 |
* timeout: number; |
| 107 |
* }} AsyncResolver |
| 108 |
*/ |
| 109 |
|
| 110 |
/** |
| 111 |
* @template [R=unknown] |
| 112 |
* @template [A=R] |
| 113 |
* @typedef {{ |
| 114 |
* acceptedType: ArgumentType | ArgumentType[]; |
| 115 |
* getFailedDetails: () => unknown[]; |
| 116 |
* mapElements: (received: Target) => ElementMap; |
| 117 |
* message: AssertionMessage; |
| 118 |
* name: string; |
| 119 |
* onFail: AssertionReportMessage; |
| 120 |
* onPass: AssertionReportMessage; |
| 121 |
* predicate: () => boolean; |
| 122 |
* }} MatcherSpecifications |
| 123 |
*/ |
| 124 |
|
| 125 |
/** |
| 126 |
* @template T |
| 127 |
* @typedef {T | Iterable<T>} MaybeIterable |
| 128 |
*/ |
| 129 |
|
| 130 |
//----------------------------------------------------------------------------- |
| 131 |
// Global |
| 132 |
//----------------------------------------------------------------------------- |
| 133 |
|
| 134 |
const { |
| 135 |
Array: { isArray: $isArray }, |
| 136 |
clearTimeout, |
| 137 |
Error, |
| 138 |
Intl: { ListFormat }, |
| 139 |
Math: { abs: $abs, floor: $floor }, |
| 140 |
Object: { assign: $assign, create: $create, entries: $entries, keys: $keys }, |
| 141 |
parseFloat, |
| 142 |
performance, |
| 143 |
Promise, |
| 144 |
setTimeout, |
| 145 |
TypeError, |
| 146 |
WeakMap, |
| 147 |
} = globalThis; |
| 148 |
/** @type {Performance["now"]} */ |
| 149 |
const $now = performance.now.bind(performance); |
| 150 |
|
| 151 |
//----------------------------------------------------------------------------- |
| 152 |
// Internal |
| 153 |
//----------------------------------------------------------------------------- |
| 154 |
|
| 155 |
/** |
| 156 |
* @param {[string, unknown][]} entries |
| 157 |
*/ |
| 158 |
function detailsFromEntries(entries) { |
| 159 |
const result = []; |
| 160 |
const expected = entries.at(-2); |
| 161 |
if (expected) { |
| 162 |
result.push(Markup.expected(expected[0] || LABEL_EXPECTED, expected[1])); |
| 163 |
} |
| 164 |
const received = entries.at(-1); |
| 165 |
if (received) { |
| 166 |
result.push(Markup.received(received[0] || LABEL_RECEIVED, received[1])); |
| 167 |
} |
| 168 |
return result; |
| 169 |
} |
| 170 |
|
| 171 |
/** |
| 172 |
* @param {...unknown} args |
| 173 |
*/ |
| 174 |
function detailsFromValues(...args) { |
| 175 |
return detailsFromEntries(args.map((arg) => [null, arg])); |
| 176 |
} |
| 177 |
|
| 178 |
/** |
| 179 |
* @param {...unknown} args |
| 180 |
*/ |
| 181 |
function detailsFromValuesWithDiff(...args) { |
| 182 |
return detailsFromValues(...args).concat(Markup.diff(...args)); |
| 183 |
} |
| 184 |
|
| 185 |
/** |
| 186 |
* @param {Error} [error] |
| 187 |
*/ |
| 188 |
function formatError(error) { |
| 189 |
let strError = error ? String(error) : ""; |
| 190 |
if (error?.cause) { |
| 191 |
strError += `\n${formatError(error.cause)}`; |
| 192 |
} |
| 193 |
return strError; |
| 194 |
} |
| 195 |
|
| 196 |
/** |
| 197 |
* @param {string} message |
| 198 |
* @param {boolean} plural |
| 199 |
* @param {boolean} not |
| 200 |
*/ |
| 201 |
function formatMessage(message, plural, not) { |
| 202 |
return message.replaceAll(R_PLURAL, plural ? "$2" : "$1").replaceAll(R_NOT, not ? "$2" : "$1"); |
| 203 |
} |
| 204 |
|
| 205 |
/** |
| 206 |
* @param {Iterable<unknown> | Record<unknown, unknown>} object |
| 207 |
*/ |
| 208 |
function getLength(object) { |
| 209 |
if (typeof object === "string" || $isArray(object)) { |
| 210 |
return object.length; |
| 211 |
} |
| 212 |
if (isIterable(object)) { |
| 213 |
return [...object].length; |
| 214 |
} |
| 215 |
return $keys(object).length; |
| 216 |
} |
| 217 |
|
| 218 |
/** |
| 219 |
* @param {number} depth amount of lines to remove from the stack |
| 220 |
*/ |
| 221 |
function getStack(depth) { |
| 222 |
const error = new Error(); |
| 223 |
if (!isFirefox()) { |
| 224 |
// remove ´Error´ in chrome |
| 225 |
depth++; |
| 226 |
} |
| 227 |
const lines = error.stack.split(R_LINE_RETURN).slice(depth + 1); // Remove `getStack` |
| 228 |
const hidden = lines.splice(MAX_STACK_LENGTH); |
| 229 |
if (hidden.length) { |
| 230 |
lines.push(`… ${hidden.length} more`); |
| 231 |
} |
| 232 |
return lines.join("\n"); |
| 233 |
} |
| 234 |
|
| 235 |
/** |
| 236 |
* @param {Node} node |
| 237 |
* @param {string[]} keys |
| 238 |
* @returns {Record<string, string>} |
| 239 |
*/ |
| 240 |
function getStyleValues(node, keys) { |
| 241 |
const nodeStyle = getStyle(node); |
| 242 |
const styleValues = $create(null); |
| 243 |
if (nodeStyle) { |
| 244 |
for (const key of keys) { |
| 245 |
styleValues[key] = nodeStyle.getPropertyValue(key) || nodeStyle[key]; |
| 246 |
} |
| 247 |
} |
| 248 |
return styleValues; |
| 249 |
} |
| 250 |
|
| 251 |
/** |
| 252 |
* @param {Iterable<unknown> | Record<unknown, unknown>} object |
| 253 |
* @param {unknown} item |
| 254 |
* @returns {boolean} |
| 255 |
*/ |
| 256 |
function includes(object, item) { |
| 257 |
if (typeof object === "string") { |
| 258 |
return object.includes(item); |
| 259 |
} |
| 260 |
if ($isArray(object)) { |
| 261 |
// Standard case: array |
| 262 |
return object.some((i) => deepEqual(i, item)); |
| 263 |
} |
| 264 |
if (isIterable(object)) { |
| 265 |
// Iterables: cast to array |
| 266 |
return includes([...object], item); |
| 267 |
} |
| 268 |
if ($isArray(item) && item.length === 2) { |
| 269 |
return includes($entries(object), item); |
| 270 |
} |
| 271 |
return item in object; |
| 272 |
} |
| 273 |
|
| 274 |
/** |
| 275 |
* @template T |
| 276 |
* @param {T[]} list |
| 277 |
* @param {string} separator |
| 278 |
* @param {string} [lastSeparator] |
| 279 |
* @returns {(T | string)[]} |
| 280 |
*/ |
| 281 |
function listJoin(list, separator, lastSeparator) { |
| 282 |
if (list.length <= 1) { |
| 283 |
return list; |
| 284 |
} |
| 285 |
|
| 286 |
const rSeparator = isLabel(separator) ? separator : makeLabel(separator, null); |
| 287 |
const rLastSeparator = lastSeparator |
| 288 |
? isLabel(lastSeparator) |
| 289 |
? lastSeparator |
| 290 |
: makeLabel(lastSeparator, null) |
| 291 |
: rSeparator; |
| 292 |
|
| 293 |
const result = []; |
| 294 |
for (let i = 0; i < list.length; i++) { |
| 295 |
if (i === list.length - 1) { |
| 296 |
result.push(rLastSeparator); |
| 297 |
} else if (i > 0) { |
| 298 |
result.push(rSeparator); |
| 299 |
} |
| 300 |
result.push(list[i]); |
| 301 |
} |
| 302 |
return result; |
| 303 |
} |
| 304 |
|
| 305 |
/** @type {typeof makeLabel} */ |
| 306 |
function makeLabelOrString(...args) { |
| 307 |
const label = makeLabel(...args); |
| 308 |
if (logger.canLog("debug")) { |
| 309 |
debugLabelCache.set(label, args[0]); |
| 310 |
} |
| 311 |
return label[1] === null ? label[0] : label; |
| 312 |
} |
| 313 |
|
| 314 |
/** |
| 315 |
* @param {string} modifier |
| 316 |
* @param {string} message |
| 317 |
*/ |
| 318 |
function matcherModifierError(modifier, message) { |
| 319 |
return new HootError(`cannot use modifier "${modifier}": ${message}`); |
| 320 |
} |
| 321 |
|
| 322 |
/** |
| 323 |
* @param {string | Record<string, unknown>} style |
| 324 |
* @param {unknown} [defaultValue] |
| 325 |
*/ |
| 326 |
function parseInlineStyle(style, defaultValue) { |
| 327 |
/** @type {Record<string, string>} */ |
| 328 |
const styleObject = $create(null); |
| 329 |
if (typeof style === "string") { |
| 330 |
for (const styleProperty of style.split(";")) { |
| 331 |
const [key, value] = styleProperty.split(":"); |
| 332 |
if (key && (value ?? defaultValue)) { |
| 333 |
styleObject[key.trim()] = value?.trim() || defaultValue; |
| 334 |
} |
| 335 |
} |
| 336 |
} else { |
| 337 |
for (const key in style) { |
| 338 |
styleObject[key] = style[key]; |
| 339 |
} |
| 340 |
} |
| 341 |
return styleObject; |
| 342 |
} |
| 343 |
|
| 344 |
/** @type {StringConstructor["raw"]} */ |
| 345 |
function r(template, ...substitutions) { |
| 346 |
return makeLabel(String.raw(template, ...substitutions), null); |
| 347 |
} |
| 348 |
|
| 349 |
/** |
| 350 |
* @param {string} method |
| 351 |
*/ |
| 352 |
function scopeError(method) { |
| 353 |
return new HootError(`cannot call \`${method}()\` outside of a test`); |
| 354 |
} |
| 355 |
|
| 356 |
/** |
| 357 |
* @param {unknown} value |
| 358 |
* @param {string | number | RegExp} matcher |
| 359 |
*/ |
| 360 |
function valueMatches(value, matcher) { |
| 361 |
if (matcher === S_ANY) { |
| 362 |
return !isNil(value); |
| 363 |
} |
| 364 |
if (isInstanceOf(matcher, RegExp)) { |
| 365 |
return matcher.test(value); |
| 366 |
} |
| 367 |
if (typeof matcher === "number") { |
| 368 |
value = parseFloat(value); |
| 369 |
} |
| 370 |
return strictEqual(value, matcher); |
| 371 |
} |
| 372 |
|
| 373 |
const AMPERSAND = makeLabel("&", null); |
| 374 |
const ARROW_RIGHT = makeLabelIcon("fa fa-arrow-right text-sm"); |
| 375 |
|
| 376 |
const R_LINE_RETURN = /\n+/g; |
| 377 |
const R_NOT = /\[([\w\s]*)!([\w\s]*)\]/g; |
| 378 |
const R_PLURAL = /\[([\w\s]*)%([\w\s]*)\]/g; |
| 379 |
|
| 380 |
const FLAGS = { |
| 381 |
error: 0b1, |
| 382 |
headless: 0b10, |
| 383 |
not: 0b100, |
| 384 |
rejects: 0b1000, |
| 385 |
resolves: 0b10000, |
| 386 |
silent: 0b100000, |
| 387 |
}; |
| 388 |
const LABEL_EXPECTED = "Expected:"; |
| 389 |
const LABEL_RECEIVED = "Received:"; |
| 390 |
/** @type {CaseEventType[]} */ |
| 391 |
const CASE_EVENT_LOG_COLORS = ["assertion", "query", "step", "time"]; |
| 392 |
const MAX_STACK_LENGTH = 10; |
| 393 |
|
| 394 |
/** @type {WeakMap<any, any>} */ |
| 395 |
const debugLabelCache = new WeakMap(); |
| 396 |
/** @type {Set<Matcher>} */ |
| 397 |
const unconsumedMatchers = new Set(); |
| 398 |
|
| 399 |
let currentStack = ""; |
| 400 |
|
| 401 |
//----------------------------------------------------------------------------- |
| 402 |
// Exports |
| 403 |
//----------------------------------------------------------------------------- |
| 404 |
|
| 405 |
/** |
| 406 |
* @param {ExpectBuilderParams} params |
| 407 |
* @returns {[typeof enrichedExpect, typeof expectHooks]} |
| 408 |
*/ |
| 409 |
export function makeExpect(params) { |
| 410 |
/** |
| 411 |
* @param {AfterTestOptions} [options] |
| 412 |
*/ |
| 413 |
function afterTest(options) { |
| 414 |
const { test } = currentResult; |
| 415 |
|
| 416 |
removeInteractionListener?.(); |
| 417 |
|
| 418 |
currentResult.done(); |
| 419 |
|
| 420 |
const { |
| 421 |
assertion: assertionCount = 0, |
| 422 |
error: errorCount = 0, |
| 423 |
query: queryCount = 0, |
| 424 |
} = currentResult.counts; |
| 425 |
|
| 426 |
// Expect without matchers |
| 427 |
if (unconsumedMatchers.size) { |
| 428 |
let times; |
| 429 |
switch (unconsumedMatchers.size) { |
| 430 |
case 1: |
| 431 |
times = [r`once`]; |
| 432 |
break; |
| 433 |
case 2: |
| 434 |
times = [r`twice`]; |
| 435 |
break; |
| 436 |
default: |
| 437 |
times = [unconsumedMatchers.size, r`times`]; |
| 438 |
} |
| 439 |
currentResult.registerEvent("assertion", { |
| 440 |
label: "expect", |
| 441 |
pass: false, |
| 442 |
reportMessage: [r`called`, ...times, r`without calling any matchers`], |
| 443 |
}); |
| 444 |
unconsumedMatchers.clear(); |
| 445 |
} |
| 446 |
|
| 447 |
// Unverified steps |
| 448 |
if (currentResult.currentSteps.length) { |
| 449 |
currentResult.registerEvent("assertion", { |
| 450 |
label: "step", |
| 451 |
docLabel: "expect.step", |
| 452 |
pass: false, |
| 453 |
failedDetails: detailsFromEntries([["Steps:", currentResult.currentSteps]]), |
| 454 |
reportMessage: [r`unverified steps`], |
| 455 |
}); |
| 456 |
} |
| 457 |
|
| 458 |
// Assertion & query event count |
| 459 |
if (!(assertionCount + queryCount)) { |
| 460 |
currentResult.registerEvent("assertion", { |
| 461 |
label: "assertions", |
| 462 |
docLabel: "expect.assertions", |
| 463 |
pass: false, |
| 464 |
reportMessage: [ |
| 465 |
r`expected at least`, |
| 466 |
1, |
| 467 |
r`assertion or query event, but none were run`, |
| 468 |
], |
| 469 |
}); |
| 470 |
} else if ( |
| 471 |
currentResult.expectedAssertions && |
| 472 |
currentResult.expectedAssertions !== assertionCount |
| 473 |
) { |
| 474 |
currentResult.registerEvent("assertion", { |
| 475 |
label: "assertions", |
| 476 |
docLabel: "expect.assertions", |
| 477 |
pass: false, |
| 478 |
reportMessage: [ |
| 479 |
r`expected`, |
| 480 |
currentResult.expectedAssertions, |
| 481 |
r`assertions, but`, |
| 482 |
assertionCount, |
| 483 |
r`were run`, |
| 484 |
], |
| 485 |
}); |
| 486 |
} |
| 487 |
|
| 488 |
// Unverified errors |
| 489 |
if (currentResult.currentErrors.length) { |
| 490 |
currentResult.registerEvent("assertion", { |
| 491 |
label: "errors", |
| 492 |
docLabel: "expect.errors", |
| 493 |
pass: false, |
| 494 |
reportMessage: [currentResult.currentErrors.length, r`unverified error(s)`], |
| 495 |
}); |
| 496 |
} |
| 497 |
|
| 498 |
// Error count |
| 499 |
if (currentResult.expectedErrors && currentResult.expectedErrors !== errorCount) { |
| 500 |
currentResult.registerEvent("assertion", { |
| 501 |
label: "errors", |
| 502 |
docLabel: "expect.errors", |
| 503 |
pass: false, |
| 504 |
reportMessage: [ |
| 505 |
r`expected`, |
| 506 |
currentResult.expectedErrors, |
| 507 |
r`errors, but`, |
| 508 |
errorCount, |
| 509 |
r`were thrown`, |
| 510 |
], |
| 511 |
}); |
| 512 |
} |
| 513 |
|
| 514 |
// "Todo" tag |
| 515 |
if (test?.config.todo) { |
| 516 |
if (currentResult.pass) { |
| 517 |
currentResult.registerEvent("assertion", { |
| 518 |
label: "TODO", |
| 519 |
pass: false, |
| 520 |
reportMessage: [r`all assertions passed: remove "todo" test modifier`], |
| 521 |
}); |
| 522 |
} else { |
| 523 |
currentResult.pass = true; |
| 524 |
} |
| 525 |
} |
| 526 |
|
| 527 |
// Abort status |
| 528 |
if (options?.aborted) { |
| 529 |
currentResult.registerEvent("assertion", { |
| 530 |
label: "aborted", |
| 531 |
pass: false, |
| 532 |
reportMessage: [r`test was aborted, results may not be relevant`], |
| 533 |
}); |
| 534 |
} |
| 535 |
|
| 536 |
if (test) { |
| 537 |
// Set test status |
| 538 |
if (options?.aborted) { |
| 539 |
test.status = Test.ABORTED; |
| 540 |
} else if (currentResult.pass) { |
| 541 |
test.status ||= Test.PASSED; |
| 542 |
} else { |
| 543 |
test.status = Test.FAILED; |
| 544 |
} |
| 545 |
|
| 546 |
/** @type {import("../hoot_utils").Reporting} */ |
| 547 |
const report = { |
| 548 |
assertions: assertionCount, |
| 549 |
duration: test.lastResults?.duration || 0, |
| 550 |
tests: 1, |
| 551 |
}; |
| 552 |
if (!currentResult.pass) { |
| 553 |
report.failed = 1; |
| 554 |
} else if (test.config.todo) { |
| 555 |
report.todo = 1; |
| 556 |
} else { |
| 557 |
report.passed = 1; |
| 558 |
} |
| 559 |
|
| 560 |
test.parent?.reporting.add(report); |
| 561 |
} |
| 562 |
|
| 563 |
const result = currentResult; |
| 564 |
if (!options?.debug) { |
| 565 |
currentResult = null; |
| 566 |
currentResultInErrorState = false; |
| 567 |
} |
| 568 |
|
| 569 |
return result; |
| 570 |
} |
| 571 |
|
| 572 |
/** |
| 573 |
* Expects the current test to have the `expected` amount of assertions. This |
| 574 |
* number cannot be less than 1. |
| 575 |
* |
| 576 |
* Note that it is generally preferred to use `expect.step` and `expect.verifySteps` |
| 577 |
* instead as it is more reliable and allows to test more extensively. |
| 578 |
* |
| 579 |
* @param {number} expected |
| 580 |
*/ |
| 581 |
function assertions(expected) { |
| 582 |
if (!currentResult) { |
| 583 |
throw scopeError("expect.assertions"); |
| 584 |
} |
| 585 |
ensureArguments(arguments, "integer"); |
| 586 |
if (expected < 1) { |
| 587 |
throw new HootError(`expected assertions count should be more than 1`); |
| 588 |
} |
| 589 |
|
| 590 |
currentResult.expectedAssertions = expected; |
| 591 |
} |
| 592 |
|
| 593 |
/** |
| 594 |
* @param {Test} test |
| 595 |
*/ |
| 596 |
function beforeTest(test) { |
| 597 |
if (test) { |
| 598 |
test.results.push(new CaseResult(test, params.headless)); |
| 599 |
|
| 600 |
// Must be retrieved from the list to be proxified |
| 601 |
currentResult = test.results.at(-1); |
| 602 |
} else { |
| 603 |
currentResult = new CaseResult(null, params.headless); |
| 604 |
} |
| 605 |
currentResultInErrorState = false; |
| 606 |
const listenedEvents = ["query"]; |
| 607 |
if (!params.headless) { |
| 608 |
listenedEvents.push("interaction", "server", "time"); |
| 609 |
} |
| 610 |
removeInteractionListener = addInteractionListener(listenedEvents, onInteraction); |
| 611 |
} |
| 612 |
|
| 613 |
/** |
| 614 |
* @param {{ errors: unknown[]; options: VerifierOptions }} resolver |
| 615 |
* @param {boolean} forceCheck |
| 616 |
*/ |
| 617 |
function checkErrors(resolver, forceCheck) { |
| 618 |
if (!resolver) { |
| 619 |
return false; |
| 620 |
} |
| 621 |
const { errors, options } = resolver; |
| 622 |
const { currentErrors } = currentResult; |
| 623 |
const pass = |
| 624 |
currentErrors.length === errors.length && |
| 625 |
currentErrors.every( |
| 626 |
(error, i) => |
| 627 |
match(error, errors[i]) || (error.cause && match(error.cause, errors[i])) |
| 628 |
); |
| 629 |
|
| 630 |
if (pass || forceCheck) { |
| 631 |
currentResult.consumeErrors(); |
| 632 |
|
| 633 |
const reportMessage = pass |
| 634 |
? errors.length |
| 635 |
? listJoin(errors, ARROW_RIGHT) |
| 636 |
: "no errors" |
| 637 |
: "expected the following errors"; |
| 638 |
const assertion = { |
| 639 |
label: "verifyErrors", |
| 640 |
docLabel: "expect.verifyErrors", |
| 641 |
message: options?.message, |
| 642 |
pass, |
| 643 |
reportMessage, |
| 644 |
}; |
| 645 |
if (!pass) { |
| 646 |
const fActual = currentErrors.map(formatError); |
| 647 |
const fExpected = errors.map(formatError); |
| 648 |
assertion.failedDetails = detailsFromValuesWithDiff(fExpected, fActual); |
| 649 |
assertion.stack = getStack(1); |
| 650 |
} |
| 651 |
currentResult.registerEvent("assertion", assertion); |
| 652 |
} |
| 653 |
|
| 654 |
return pass; |
| 655 |
} |
| 656 |
|
| 657 |
/** |
| 658 |
* @param {{ steps: unknown[]; options: VerifierOptions } | null} resolver |
| 659 |
* @param {boolean} forceCheck |
| 660 |
*/ |
| 661 |
function checkSteps(resolver, forceCheck) { |
| 662 |
if (!resolver) { |
| 663 |
return false; |
| 664 |
} |
| 665 |
const { steps, options } = resolver; |
| 666 |
const receivedSteps = currentResult.currentSteps; |
| 667 |
const pass = deepEqual(steps, receivedSteps, options); |
| 668 |
|
| 669 |
if (pass || forceCheck) { |
| 670 |
currentResult.consumeSteps(); |
| 671 |
|
| 672 |
const separator = options?.ignoreOrder ? AMPERSAND : ARROW_RIGHT; |
| 673 |
const reportMessage = pass |
| 674 |
? receivedSteps.length |
| 675 |
? listJoin(receivedSteps, separator) |
| 676 |
: "no steps" |
| 677 |
: "expected the following steps"; |
| 678 |
const assertion = { |
| 679 |
label: "verifySteps", |
| 680 |
docLabel: "expect.verifySteps", |
| 681 |
message: options?.message, |
| 682 |
pass, |
| 683 |
reportMessage, |
| 684 |
}; |
| 685 |
if (!pass) { |
| 686 |
assertion.failedDetails = detailsFromValuesWithDiff(steps, receivedSteps); |
| 687 |
assertion.stack = getStack(1); |
| 688 |
} |
| 689 |
currentResult.registerEvent("assertion", assertion); |
| 690 |
} |
| 691 |
|
| 692 |
return pass; |
| 693 |
} |
| 694 |
|
| 695 |
/** |
| 696 |
* Expects the current test to have the `expected` amount of errors. |
| 697 |
* |
| 698 |
* This also means that from the moment this function is called, the test will |
| 699 |
* accept that amount of errors before being considered as failed. |
| 700 |
* |
| 701 |
* @param {number} expected |
| 702 |
*/ |
| 703 |
function errors(expected) { |
| 704 |
if (!currentResult) { |
| 705 |
throw scopeError("expect.errors"); |
| 706 |
} |
| 707 |
ensureArguments(arguments, "integer"); |
| 708 |
|
| 709 |
currentResult.expectedErrors = expected; |
| 710 |
} |
| 711 |
|
| 712 |
/** |
| 713 |
* @param {Error} error |
| 714 |
* @returns {boolean} `true` if the error can be ignored |
| 715 |
*/ |
| 716 |
function onError(error) { |
| 717 |
if (!currentResult) { |
| 718 |
return false; |
| 719 |
} |
| 720 |
|
| 721 |
currentResult.registerEvent("error", error); |
| 722 |
currentResultInErrorState = |
| 723 |
currentResult.expectedErrors < (currentResult.counts.error || 0); |
| 724 |
|
| 725 |
checkErrors(currentResult.errorResolver, false); |
| 726 |
|
| 727 |
return !currentResultInErrorState; |
| 728 |
} |
| 729 |
|
| 730 |
/** |
| 731 |
* @param {CustomEvent<InteractionDetails>} event |
| 732 |
*/ |
| 733 |
function onInteraction({ detail, type }) { |
| 734 |
if (!currentResult) { |
| 735 |
return; |
| 736 |
} |
| 737 |
|
| 738 |
currentResult.registerEvent(type, detail); |
| 739 |
} |
| 740 |
|
| 741 |
/** |
| 742 |
* Registers a step for the current test, that can be consumed by `expect.verifySteps`. |
| 743 |
* Unconsumed steps will fail the test. |
| 744 |
* |
| 745 |
* @param {unknown} value |
| 746 |
*/ |
| 747 |
function step(value) { |
| 748 |
if (!currentResult) { |
| 749 |
throw scopeError("expect.step"); |
| 750 |
} |
| 751 |
|
| 752 |
currentResult.registerEvent("step", value); |
| 753 |
|
| 754 |
checkSteps(currentResult.stepResolver, false); |
| 755 |
} |
| 756 |
|
| 757 |
/** |
| 758 |
* Expects the received matchers to match the errors thrown since the start |
| 759 |
* of the test or the last call to {@link verifyErrors}. Calling this matcher |
| 760 |
* will reset the list of current errors. |
| 761 |
* |
| 762 |
* `expect.errors(...)` should be called before function |
| 763 |
* |
| 764 |
* @param {unknown[]} errors |
| 765 |
* @param {VerifierOptions} [options] |
| 766 |
* @returns {boolean} |
| 767 |
* @example |
| 768 |
* expect.verifyErrors([/RPCError/, /Invalid domain AST/]); |
| 769 |
*/ |
| 770 |
function verifyErrors(errors, options) { |
| 771 |
if (!currentResult) { |
| 772 |
throw scopeError("expect.verifyErrors"); |
| 773 |
} |
| 774 |
ensureArguments(arguments, "any[]", ["object", null]); |
| 775 |
if (errors.length > currentResult.expectedErrors) { |
| 776 |
throw new HootError( |
| 777 |
`cannot call \`expect.verifyErrors()\` without calling \`expect.errors()\` beforehand` |
| 778 |
); |
| 779 |
} |
| 780 |
|
| 781 |
return checkErrors({ errors, options }, true); |
| 782 |
} |
| 783 |
|
| 784 |
/** |
| 785 |
* Expects the received steps to be equal to the steps emitted since the start |
| 786 |
* of the test or the last call to {@link verifySteps}. Calling this matcher |
| 787 |
* will reset the list of current steps. |
| 788 |
* |
| 789 |
* @param {unknown[]} steps |
| 790 |
* @param {VerifierOptions} [options] |
| 791 |
* @returns {boolean} |
| 792 |
* @example |
| 793 |
* expect.step("web_read_group"); |
| 794 |
* expect.step([1, 2]); |
| 795 |
* expect.verifySteps(["web_read_group", "web_search_read"]); |
| 796 |
*/ |
| 797 |
function verifySteps(steps, options) { |
| 798 |
if (!currentResult) { |
| 799 |
throw scopeError("expect.verifySteps"); |
| 800 |
} |
| 801 |
ensureArguments(arguments, "any[]", ["object", null]); |
| 802 |
|
| 803 |
return checkSteps({ steps, options }, true); |
| 804 |
} |
| 805 |
|
| 806 |
/** |
| 807 |
* Same as {@link verifyErrors}, but will not immediatly fail if errors are |
| 808 |
* not caught yet, and will instead wait for a certain timeout (default: 2000ms) |
| 809 |
* to allow errors to be caught later. |
| 810 |
* |
| 811 |
* Checks are performed initially, at the end of the timeout, and each time |
| 812 |
* an error is detected. |
| 813 |
* |
| 814 |
* @param {unknown[]} errors |
| 815 |
* @param {AsyncVerifierOptions} [options] |
| 816 |
* @returns {Promise<boolean>} |
| 817 |
* @example |
| 818 |
* fetch("invalid/url"); |
| 819 |
* await expect.waitForErrors([/RPCError/]); |
| 820 |
*/ |
| 821 |
function waitForErrors(errors, options) { |
| 822 |
if (!currentResult) { |
| 823 |
throw scopeError("expect.waitForErrors"); |
| 824 |
} |
| 825 |
ensureArguments(arguments, "any[]", ["object", null]); |
| 826 |
|
| 827 |
// Run check for any current resolver (if any) |
| 828 |
checkErrors(currentResult.errorResolver, true); |
| 829 |
|
| 830 |
// Run early check if conditions are already met |
| 831 |
if (checkErrors({ errors, options }, false)) { |
| 832 |
return true; |
| 833 |
} |
| 834 |
|
| 835 |
currentResult.errorResolver = { |
| 836 |
...Promise.withResolvers(), |
| 837 |
errors, |
| 838 |
options, |
| 839 |
timeout: setTimeout( |
| 840 |
() => checkErrors(currentResult.errorResolver, true), |
| 841 |
options?.timeout ?? 2000 |
| 842 |
), |
| 843 |
}; |
| 844 |
return currentResult.errorResolver.promise; |
| 845 |
} |
| 846 |
|
| 847 |
/** |
| 848 |
* Same as {@link verifySteps}, but will not immediatly fail if steps have not |
| 849 |
* been registered yet, and will instead wait for a certain timeout (default: |
| 850 |
* 2000ms) to allow steps to be registered later. |
| 851 |
* |
| 852 |
* Checks are performed initially, at the end of the timeout, and each time |
| 853 |
* a step is registered. |
| 854 |
* |
| 855 |
* @param {unknown[]} steps |
| 856 |
* @param {AsyncVerifierOptions} [options] |
| 857 |
* @returns {Promise<boolean>} |
| 858 |
* @example |
| 859 |
* fetch(".../call_kw/web_read_group"); |
| 860 |
* await expect.waitForSteps(["web_read_group"]); |
| 861 |
*/ |
| 862 |
async function waitForSteps(steps, options) { |
| 863 |
if (!currentResult) { |
| 864 |
throw scopeError("expect.waitForSteps"); |
| 865 |
} |
| 866 |
ensureArguments(arguments, "any[]", ["object", null]); |
| 867 |
|
| 868 |
// Run check for any current resolver (if any) |
| 869 |
checkSteps(currentResult.stepResolver, true); |
| 870 |
|
| 871 |
// Run early check if conditions are already met |
| 872 |
if (checkSteps({ steps, options }, false)) { |
| 873 |
return true; |
| 874 |
} |
| 875 |
|
| 876 |
currentResult.stepResolver = { |
| 877 |
...Promise.withResolvers(), |
| 878 |
steps, |
| 879 |
options, |
| 880 |
timeout: setTimeout( |
| 881 |
() => checkSteps(currentResult.stepResolver, true), |
| 882 |
options?.timeout ?? 2000 |
| 883 |
), |
| 884 |
}; |
| 885 |
return currentResult.stepResolver.promise; |
| 886 |
} |
| 887 |
|
| 888 |
/** |
| 889 |
* Main entry point to write assertions in tests. |
| 890 |
* |
| 891 |
* This function takes a value whose expected type depends on the following |
| 892 |
* matcher. See the documentation of each matcher for more information. |
| 893 |
* |
| 894 |
* Note that this function can only be called inside of a test. |
| 895 |
* |
| 896 |
* @template [R=unknown] |
| 897 |
* @param {R} received |
| 898 |
* @example |
| 899 |
* expect([1, 2, 3]).toEqual([1, 2, 3]); |
| 900 |
*/ |
| 901 |
function expect(received) { |
| 902 |
if (arguments.length > 1) { |
| 903 |
throw new HootError(`\`expect()\` only accepts a single argument`); |
| 904 |
} |
| 905 |
|
| 906 |
if (!currentResult) { |
| 907 |
throw scopeError("expect"); |
| 908 |
} |
| 909 |
|
| 910 |
let flags = 0; |
| 911 |
if (currentResultInErrorState) { |
| 912 |
flags |= FLAGS.error; |
| 913 |
} |
| 914 |
if (params.headless) { |
| 915 |
flags |= FLAGS.headless; |
| 916 |
} |
| 917 |
|
| 918 |
return new Matcher(currentResult, received, flags); |
| 919 |
} |
| 920 |
|
| 921 |
const enrichedExpect = $assign(expect, { |
| 922 |
assertions, |
| 923 |
errors, |
| 924 |
step, |
| 925 |
verifyErrors, |
| 926 |
verifySteps, |
| 927 |
waitForErrors, |
| 928 |
waitForSteps, |
| 929 |
}); |
| 930 |
const expectHooks = { |
| 931 |
after: afterTest, |
| 932 |
before: beforeTest, |
| 933 |
error: onError, |
| 934 |
}; |
| 935 |
|
| 936 |
/** @type {CaseResult | null} */ |
| 937 |
let currentResult = null; |
| 938 |
let currentResultInErrorState = false; |
| 939 |
|
| 940 |
let removeInteractionListener; |
| 941 |
|
| 942 |
return [enrichedExpect, expectHooks]; |
| 943 |
} |
| 944 |
|
| 945 |
export class CaseResult { |
| 946 |
duration = 0; |
| 947 |
pass = true; |
| 948 |
/** @type {Test | null} */ |
| 949 |
test = null; |
| 950 |
ts = $floor($now()); |
| 951 |
|
| 952 |
/** @type {CaseEvent[]} */ |
| 953 |
events = []; |
| 954 |
/** @type {Partial<Record<CaseEventType, number>>} */ |
| 955 |
counts = $create(null); |
| 956 |
|
| 957 |
expectedAssertions = 0; |
| 958 |
expectedErrors = 0; |
| 959 |
|
| 960 |
currentErrors = []; |
| 961 |
currentSteps = []; |
| 962 |
/** @type {AsyncResolver<{ errors: unknown[] }> | null} */ |
| 963 |
errorResolver = null; |
| 964 |
/** @type {AsyncResolver<{ steps: unknown[] }> | null} */ |
| 965 |
stepResolver = null; |
| 966 |
|
| 967 |
/** |
| 968 |
* @param {Test | null} [test] |
| 969 |
* @param {boolean} [headless] |
| 970 |
*/ |
| 971 |
constructor(test, headless) { |
| 972 |
if (test) { |
| 973 |
this.test = test; |
| 974 |
} |
| 975 |
|
| 976 |
this.headless = !!headless; |
| 977 |
|
| 978 |
markRaw(this); |
| 979 |
} |
| 980 |
|
| 981 |
consumeErrors() { |
| 982 |
if (this.errorResolver) { |
| 983 |
clearTimeout(this.errorResolver.timeout); |
| 984 |
this.errorResolver.resolve(true); |
| 985 |
this.errorResolver = null; |
| 986 |
} |
| 987 |
this.currentErrors = []; |
| 988 |
} |
| 989 |
|
| 990 |
consumeSteps() { |
| 991 |
if (this.stepResolver) { |
| 992 |
clearTimeout(this.stepResolver.timeout); |
| 993 |
this.stepResolver.resolve(true); |
| 994 |
this.stepResolver = null; |
| 995 |
} |
| 996 |
this.currentSteps = []; |
| 997 |
} |
| 998 |
|
| 999 |
/** |
| 1000 |
* @param {CaseEventType} type |
| 1001 |
*/ |
| 1002 |
getEvents(type) { |
| 1003 |
const nType = typeof type === "number" ? type : CASE_EVENT_TYPES[type].value; |
| 1004 |
return this.events.filter((event) => event.type & nType); |
| 1005 |
} |
| 1006 |
|
| 1007 |
done() { |
| 1008 |
this.duration = $floor($now()) - this.ts; |
| 1009 |
} |
| 1010 |
|
| 1011 |
/** |
| 1012 |
* |
| 1013 |
* @param {CaseEventType} type |
| 1014 |
* @param {unknown} value |
| 1015 |
*/ |
| 1016 |
registerEvent(type, value) { |
| 1017 |
let caseEvent; |
| 1018 |
this.counts[type] ||= 0; |
| 1019 |
this.counts[type]++; |
| 1020 |
switch (type) { |
| 1021 |
case "assertion": { |
| 1022 |
if (value && this.headless) { |
| 1023 |
delete value.docLabel; // Only required in UI |
| 1024 |
} |
| 1025 |
caseEvent = new Assertion(this.counts.assertion, value); |
| 1026 |
this.pass &&= caseEvent.pass; |
| 1027 |
break; |
| 1028 |
} |
| 1029 |
case "error": { |
| 1030 |
caseEvent = new CaseError(value); |
| 1031 |
this.currentErrors.push(value); |
| 1032 |
break; |
| 1033 |
} |
| 1034 |
case "step": { |
| 1035 |
if (!this.headless) { |
| 1036 |
caseEvent = new Step(value); |
| 1037 |
} |
| 1038 |
this.currentSteps.push(deepCopy(value)); |
| 1039 |
break; |
| 1040 |
} |
| 1041 |
default: { |
| 1042 |
if (!this.headless || type === "query") { |
| 1043 |
caseEvent = new DOMCaseEvent(type, value); |
| 1044 |
} |
| 1045 |
break; |
| 1046 |
} |
| 1047 |
} |
| 1048 |
if (caseEvent) { |
| 1049 |
if (logger.canLog("debug") && CASE_EVENT_LOG_COLORS.includes(type)) { |
| 1050 |
const colorName = caseEvent.pass === false ? "rose" : CASE_EVENT_TYPES[type].color; |
| 1051 |
const logArgs = [[caseEvent.label, getColorHex(colorName)]]; |
| 1052 |
for (const part of caseEvent.message) { |
| 1053 |
if (isLabel(part)) { |
| 1054 |
// Get and consume cached original values |
| 1055 |
logArgs.push(debugLabelCache.get(part) ?? part[0]); |
| 1056 |
debugLabelCache.delete(part); |
| 1057 |
} else { |
| 1058 |
logArgs.push(part); |
| 1059 |
} |
| 1060 |
} |
| 1061 |
if (caseEvent.additionalMessage) { |
| 1062 |
logArgs.push("\n", { message: caseEvent.additionalMessage }); |
| 1063 |
} |
| 1064 |
logger.logTestEvent(...logArgs); |
| 1065 |
} |
| 1066 |
this.events.push(caseEvent); |
| 1067 |
} |
| 1068 |
} |
| 1069 |
} |
| 1070 |
|
| 1071 |
/** |
| 1072 |
* @template R |
| 1073 |
* @template [A=R] |
| 1074 |
* @template [Async=false] |
| 1075 |
*/ |
| 1076 |
export class Matcher { |
| 1077 |
/** |
| 1078 |
* @private |
| 1079 |
* @type {number} |
| 1080 |
*/ |
| 1081 |
_flags = 0; |
| 1082 |
/** |
| 1083 |
* @private |
| 1084 |
* @type {R} |
| 1085 |
*/ |
| 1086 |
_received = null; |
| 1087 |
/** |
| 1088 |
* @private |
| 1089 |
* @type {CaseResult} |
| 1090 |
*/ |
| 1091 |
_result; |
| 1092 |
|
| 1093 |
/** |
| 1094 |
* @param {CaseResult} result |
| 1095 |
* @param {R} received |
| 1096 |
* @param {number} flags |
| 1097 |
*/ |
| 1098 |
constructor(result, received, flags) { |
| 1099 |
this._flags = flags; |
| 1100 |
this._result = result; |
| 1101 |
this._received = received; |
| 1102 |
|
| 1103 |
unconsumedMatchers.add(this); |
| 1104 |
} |
| 1105 |
|
| 1106 |
//------------------------------------------------------------------------- |
| 1107 |
// Modifiers |
| 1108 |
//------------------------------------------------------------------------- |
| 1109 |
|
| 1110 |
/** |
| 1111 |
* Returns a set of matchers expecting a result opposite to what normal matchers |
| 1112 |
* would expect. |
| 1113 |
* |
| 1114 |
* @returns {Omit<Matcher<R, A, Async>, "not">} |
| 1115 |
* @example |
| 1116 |
* expect([1]).not.toBeEmpty(); |
| 1117 |
* @example |
| 1118 |
* expect("foo").not.toBe("bar"); |
| 1119 |
*/ |
| 1120 |
get not() { |
| 1121 |
if (this._flags & FLAGS.not) { |
| 1122 |
throw matcherModifierError("not", `matcher is already negated`); |
| 1123 |
} |
| 1124 |
return this._clone(FLAGS.not); |
| 1125 |
} |
| 1126 |
|
| 1127 |
/** |
| 1128 |
* Returns a set of matchers which will await the received value as a promise |
| 1129 |
* and will be applied to a value rejected by that promise. The matcher will |
| 1130 |
* throw an error should the promise resolve instead of being rejected. |
| 1131 |
* |
| 1132 |
* @returns {Omit<Matcher<R, A, true>, "rejects" | "resolves">} |
| 1133 |
* @example |
| 1134 |
* await expect(Promise.reject("foo")).rejects.toBe("foo"); |
| 1135 |
*/ |
| 1136 |
get rejects() { |
| 1137 |
if (this._flags & (FLAGS.rejects | FLAGS.resolves)) { |
| 1138 |
throw matcherModifierError( |
| 1139 |
"rejects", |
| 1140 |
`matcher value has already been wrapped in a promise resolver` |
| 1141 |
); |
| 1142 |
} |
| 1143 |
return this._clone(FLAGS.rejects); |
| 1144 |
} |
| 1145 |
|
| 1146 |
/** |
| 1147 |
* Returns a set of matchers which will await the received value as a promise |
| 1148 |
* and will be applied to a value resolved by that promise. The matcher will |
| 1149 |
* throw an error should the promise reject instead of being resolved. |
| 1150 |
* |
| 1151 |
* @returns {Omit<Matcher<R, A, true>, "rejects" | "resolves">} |
| 1152 |
* @example |
| 1153 |
* await expect(Promise.resolve("foo")).resolves.toBe("foo"); |
| 1154 |
*/ |
| 1155 |
get resolves() { |
| 1156 |
if (this._flags & (FLAGS.rejects | FLAGS.resolves)) { |
| 1157 |
throw matcherModifierError( |
| 1158 |
"resolves", |
| 1159 |
`matcher value has already been wrapped in a promise resolver` |
| 1160 |
); |
| 1161 |
} |
| 1162 |
return this._clone(FLAGS.resolves); |
| 1163 |
} |
| 1164 |
|
| 1165 |
//------------------------------------------------------------------------- |
| 1166 |
// Standard matchers |
| 1167 |
//------------------------------------------------------------------------- |
| 1168 |
|
| 1169 |
/** |
| 1170 |
* Expects the received value to be *strictly* equal to the `expected` value. |
| 1171 |
* |
| 1172 |
* @param {R} expected |
| 1173 |
* @param {ExpectOptions} [options] |
| 1174 |
* @example |
| 1175 |
* expect("foo").toBe("foo"); |
| 1176 |
* @example |
| 1177 |
* expect({ foo: 1 }).not.toBe({ foo: 1 }); |
| 1178 |
*/ |
| 1179 |
toBe(expected, options) { |
| 1180 |
this._ensureArguments(arguments, "any"); |
| 1181 |
|
| 1182 |
return this._resolve(() => ({ |
| 1183 |
name: "toBe", |
| 1184 |
acceptedType: "any", |
| 1185 |
predicate: (received) => strictEqual(expected, received), |
| 1186 |
message: options?.message, |
| 1187 |
onPass: () => [r`received value is[! not] strictly equal to`, this._received], |
| 1188 |
onFail: () => [r`expected values to be strictly equal`], |
| 1189 |
getFailedDetails: (received) => detailsFromValuesWithDiff(expected, received), |
| 1190 |
})); |
| 1191 |
} |
| 1192 |
|
| 1193 |
/** |
| 1194 |
* Expects the received value to be close to the `expected` value by a given |
| 1195 |
* margin (i.e. the maximum difference allowed between the 2, default is 1). |
| 1196 |
* |
| 1197 |
* Note: the margin is exclusive; it should be strictly larger than the diff. |
| 1198 |
* |
| 1199 |
* @param {R} expected |
| 1200 |
* @param {ExpectOptions & { margin?: number }} [options] |
| 1201 |
* @example |
| 1202 |
* expect(0.2 + 0.1).toBeCloseTo(0.3); |
| 1203 |
* @example |
| 1204 |
* expect(3.51).toBeCloseTo(3.5, { margin: 0.1 }); |
| 1205 |
*/ |
| 1206 |
toBeCloseTo(expected, options) { |
| 1207 |
this._ensureArguments(arguments, "number"); |
| 1208 |
|
| 1209 |
const margin = options?.margin ?? 1; |
| 1210 |
return this._resolve(() => ({ |
| 1211 |
name: "toBeCloseTo", |
| 1212 |
acceptedType: "number", |
| 1213 |
predicate: (received) => $abs(expected - received) < margin, |
| 1214 |
message: options?.message, |
| 1215 |
onPass: () => [r`received value is[! not] close to`, this._received], |
| 1216 |
onFail: () => [r`expected values to be close to the given value`], |
| 1217 |
getFailedDetails: (received) => detailsFromValuesWithDiff(expected, received), |
| 1218 |
})); |
| 1219 |
} |
| 1220 |
|
| 1221 |
/** |
| 1222 |
* Expects the received value to be empty: |
| 1223 |
* - `iterable`: no items |
| 1224 |
* - `object`: no keys |
| 1225 |
* - `node`: no content (i.e. no value or text) |
| 1226 |
* - anything else: falsy value (`false`, `0`, `""`, `null`, `undefined`) |
| 1227 |
* |
| 1228 |
* @param {ExpectOptions} [options] |
| 1229 |
* @example |
| 1230 |
* expect({}).toBeEmpty(); |
| 1231 |
* @example |
| 1232 |
* expect(["a", "b"]).not.toBeEmpty(); |
| 1233 |
* @example |
| 1234 |
* expect(queryOne("input")).toBeEmpty(); |
| 1235 |
*/ |
| 1236 |
toBeEmpty(options) { |
| 1237 |
this._ensureArguments(arguments); |
| 1238 |
|
| 1239 |
return this._resolve(() => ({ |
| 1240 |
name: "toBeEmpty", |
| 1241 |
acceptedType: ["any"], |
| 1242 |
predicate: (received) => isEmpty(received), |
| 1243 |
message: options?.message, |
| 1244 |
onPass: () => [this._received, r`should[! not] be empty`], |
| 1245 |
onFail: () => [this._received, r`is[! not] empty`], |
| 1246 |
getFailedDetails: detailsFromValues, |
| 1247 |
})); |
| 1248 |
} |
| 1249 |
|
| 1250 |
/** |
| 1251 |
* Expects the received value to be strictly greater than `min`. |
| 1252 |
* |
| 1253 |
* @param {number} min |
| 1254 |
* @param {ExpectOptions} [options] |
| 1255 |
* @example |
| 1256 |
* expect(5).toBeGreaterThan(-1); |
| 1257 |
* @example |
| 1258 |
* expect(4 + 2).toBeGreaterThan(5); |
| 1259 |
*/ |
| 1260 |
toBeGreaterThan(min, options) { |
| 1261 |
this._ensureArguments(arguments, "number"); |
| 1262 |
|
| 1263 |
return this._resolve(() => ({ |
| 1264 |
name: "toBeGreaterThan", |
| 1265 |
acceptedType: "number", |
| 1266 |
predicate: (received) => min < received, |
| 1267 |
message: options?.message, |
| 1268 |
onPass: () => [this._received, r`is[! not] strictly greater than`, min], |
| 1269 |
onFail: () => [r`expected value[! not] to be strictly greater`], |
| 1270 |
getFailedDetails: (received) => |
| 1271 |
detailsFromEntries([ |
| 1272 |
["Minimum:", min], |
| 1273 |
[null, received], |
| 1274 |
]), |
| 1275 |
})); |
| 1276 |
} |
| 1277 |
|
| 1278 |
/** |
| 1279 |
* Expects the received value to be an instance of the given `cls`. |
| 1280 |
* |
| 1281 |
* @param {Function} cls |
| 1282 |
* @param {ExpectOptions} [options] |
| 1283 |
* @example |
| 1284 |
* expect({ foo: 1 }).not.toBeInstanceOf(Object); |
| 1285 |
* @example |
| 1286 |
* expect(document.createElement("div")).toBeInstanceOf(HTMLElement); |
| 1287 |
*/ |
| 1288 |
toBeInstanceOf(cls, options) { |
| 1289 |
this._ensureArguments(arguments, "function"); |
| 1290 |
|
| 1291 |
return this._resolve(() => ({ |
| 1292 |
name: "toBeInstanceOf", |
| 1293 |
acceptedType: "any", |
| 1294 |
predicate: (received) => isInstanceOf(received, cls), |
| 1295 |
message: options?.message, |
| 1296 |
onPass: () => [this._received, r`is[! not] an instance of`, cls], |
| 1297 |
onFail: () => [r`expected value[! not] to be an instance of the given class`], |
| 1298 |
getFailedDetails: (received) => |
| 1299 |
detailsFromEntries([ |
| 1300 |
[null, cls], |
| 1301 |
["Actual parent class:", getConstructor(received).name], |
| 1302 |
]), |
| 1303 |
})); |
| 1304 |
} |
| 1305 |
|
| 1306 |
/** |
| 1307 |
* Expects the received value to be strictly less than `max`. |
| 1308 |
* |
| 1309 |
* @param {number} max |
| 1310 |
* @param {ExpectOptions} [options] |
| 1311 |
* @example |
| 1312 |
* expect(5).toBeLessThan(10); |
| 1313 |
* @example |
| 1314 |
* expect(8 - 6).toBeLessThan(3); |
| 1315 |
*/ |
| 1316 |
toBeLessThan(max, options) { |
| 1317 |
this._ensureArguments(arguments, "number"); |
| 1318 |
|
| 1319 |
return this._resolve(() => ({ |
| 1320 |
name: "toBeLessThan", |
| 1321 |
acceptedType: "number", |
| 1322 |
predicate: (received) => received < max, |
| 1323 |
message: options?.message, |
| 1324 |
onPass: () => [this._received, r`is[! not] strictly less than`, max], |
| 1325 |
onFail: () => [r`expected value[! not] to be strictly less`], |
| 1326 |
getFailedDetails: (received) => |
| 1327 |
detailsFromEntries([ |
| 1328 |
["Maximum:", max], |
| 1329 |
[null, received], |
| 1330 |
]), |
| 1331 |
})); |
| 1332 |
} |
| 1333 |
|
| 1334 |
/** |
| 1335 |
* Expects the received value to be of the given `type`. |
| 1336 |
* |
| 1337 |
* @param {ArgumentType} type |
| 1338 |
* @param {ExpectOptions} [options] |
| 1339 |
* @example |
| 1340 |
* expect("foo").toBeOfType("string"); |
| 1341 |
* @example |
| 1342 |
* expect({ foo: 1 }).toBeOfType("object"); |
| 1343 |
*/ |
| 1344 |
toBeOfType(type, options) { |
| 1345 |
this._ensureArguments(arguments, "string"); |
| 1346 |
|
| 1347 |
return this._resolve(() => ({ |
| 1348 |
name: "toBeOfType", |
| 1349 |
acceptedType: "any", |
| 1350 |
predicate: (received) => isOfType(received, type), |
| 1351 |
message: options?.message, |
| 1352 |
onPass: () => [this._received, r`is[! not] of type`, type], |
| 1353 |
onFail: () => [r`expected value to be of the given type`], |
| 1354 |
getFailedDetails: (received) => |
| 1355 |
detailsFromEntries([ |
| 1356 |
["Expected type:", type], |
| 1357 |
["Received value:", received], |
| 1358 |
]), |
| 1359 |
})); |
| 1360 |
} |
| 1361 |
|
| 1362 |
/** |
| 1363 |
* Expects the received value to be strictly between `min` and `max` (both inclusive). |
| 1364 |
* |
| 1365 |
* @param {number} min (inclusive) |
| 1366 |
* @param {number} max (inclusive) |
| 1367 |
* @param {ExpectOptions} [options] |
| 1368 |
* @example |
| 1369 |
* expect(3).toBeWithin(3, 9); |
| 1370 |
* @example |
| 1371 |
* expect(-8.5).toBeWithin(-20, 0); |
| 1372 |
* @example |
| 1373 |
* expect(100).toBeWithin(50, 100); |
| 1374 |
*/ |
| 1375 |
toBeWithin(min, max, options) { |
| 1376 |
this._ensureArguments(arguments, "number", "number"); |
| 1377 |
|
| 1378 |
if (min > max) { |
| 1379 |
[min, max] = [max, min]; |
| 1380 |
} |
| 1381 |
if (min === max) { |
| 1382 |
throw new HootError(`min and max cannot be equal (did you mean to use \`toBe()\`?)`); |
| 1383 |
} |
| 1384 |
|
| 1385 |
return this._resolve(() => ({ |
| 1386 |
name: "toBeWithin", |
| 1387 |
acceptedType: "number", |
| 1388 |
predicate: (received) => min <= received && received <= max, |
| 1389 |
message: options?.message, |
| 1390 |
onPass: () => [this._received, r`is[! not] between`, min, r`and`, max], |
| 1391 |
onFail: () => [r`expected value[! not] to be between given range`], |
| 1392 |
getFailedDetails: (received) => detailsFromValues(`${min} - ${max}`, received), |
| 1393 |
})); |
| 1394 |
} |
| 1395 |
|
| 1396 |
/** |
| 1397 |
* Expects the received value to be *deeply* equal to the `expected` value. |
| 1398 |
* |
| 1399 |
* @param {R} expected |
| 1400 |
* @param {ExpectOptions & DeepEqualOptions} [options] |
| 1401 |
* @example |
| 1402 |
* expect(["foo"]).toEqual(["foo"]); |
| 1403 |
* @example |
| 1404 |
* expect({ foo: 1 }).toEqual({ foo: 1 }); |
| 1405 |
*/ |
| 1406 |
toEqual(expected, options) { |
| 1407 |
this._ensureArguments(arguments, "any"); |
| 1408 |
|
| 1409 |
return this._resolve(() => ({ |
| 1410 |
name: "toEqual", |
| 1411 |
acceptedType: "any", |
| 1412 |
predicate: (received) => deepEqual(expected, received, options), |
| 1413 |
message: options?.message, |
| 1414 |
onPass: () => [r`received value is[! not] deeply equal to`, this._received], |
| 1415 |
onFail: () => [r`expected values to[! not] be deeply equal`], |
| 1416 |
getFailedDetails: (received) => detailsFromValuesWithDiff(expected, received), |
| 1417 |
})); |
| 1418 |
} |
| 1419 |
|
| 1420 |
/** |
| 1421 |
* Expects the received value to have a length of the given `length`. |
| 1422 |
* |
| 1423 |
* Received value can be a string, an iterable or an object. |
| 1424 |
* |
| 1425 |
* @param {number} length |
| 1426 |
* @param {ExpectOptions} [options] |
| 1427 |
* @example |
| 1428 |
* expect("foo").toHaveLength(3); |
| 1429 |
* @example |
| 1430 |
* expect([1, 2, 3]).toHaveLength(3); |
| 1431 |
* @example |
| 1432 |
* expect({ foo: 1, bar: 2 }).toHaveLength(2); |
| 1433 |
* @example |
| 1434 |
* expect(new Set([1, 2])).toHaveLength(2); |
| 1435 |
*/ |
| 1436 |
toHaveLength(length, options) { |
| 1437 |
this._ensureArguments(arguments, "integer"); |
| 1438 |
|
| 1439 |
return this._resolve(() => { |
| 1440 |
const receivedLength = getLength(this._received); |
| 1441 |
return { |
| 1442 |
name: "toHaveLength", |
| 1443 |
acceptedType: ["string", "array", "object"], |
| 1444 |
predicate: () => strictEqual(receivedLength, length), |
| 1445 |
message: options?.message, |
| 1446 |
onPass: () => [this._received, r`has[! not] a length of`, length], |
| 1447 |
onFail: () => [r`expected value[! not] to have the given length`], |
| 1448 |
getFailedDetails: () => |
| 1449 |
detailsFromEntries([ |
| 1450 |
["Expected length:", length], |
| 1451 |
[null, receivedLength], |
| 1452 |
]), |
| 1453 |
}; |
| 1454 |
}); |
| 1455 |
} |
| 1456 |
|
| 1457 |
/** |
| 1458 |
* Expects the received value to include an `item` of a given shape. |
| 1459 |
* |
| 1460 |
* Received value can be an iterable or an object (in case it is an object, |
| 1461 |
* the `item` should be a key or a tuple representing an entry in that object). |
| 1462 |
* |
| 1463 |
* Note that it is NOT a strict comparison: the item will be matched for deep |
| 1464 |
* equality against each item of the iterable. |
| 1465 |
* |
| 1466 |
* @param {keyof R | R[number]} item |
| 1467 |
* @param {ExpectOptions} [options] |
| 1468 |
* @example |
| 1469 |
* expect([1, 2, 3]).toInclude(2); |
| 1470 |
* @example |
| 1471 |
* expect({ foo: 1, bar: 2 }).toInclude("foo"); |
| 1472 |
* @example |
| 1473 |
* expect({ foo: 1, bar: 2 }).toInclude(["foo", 1]); |
| 1474 |
* @example |
| 1475 |
* expect(new Set([{ foo: 1 }, { bar: 2 }])).toInclude({ bar: 2 }); |
| 1476 |
*/ |
| 1477 |
toInclude(item, options) { |
| 1478 |
this._ensureArguments(arguments, "any"); |
| 1479 |
|
| 1480 |
return this._resolve(() => ({ |
| 1481 |
name: "toInclude", |
| 1482 |
acceptedType: ["string", "any[]", "object"], |
| 1483 |
predicate: (received) => includes(received, item), |
| 1484 |
message: options?.message, |
| 1485 |
onPass: () => [this._received, r`[includes!does not include]`, item], |
| 1486 |
onFail: () => [r`expected object[! not] to include the given item`], |
| 1487 |
getFailedDetails: (received) => |
| 1488 |
detailsFromEntries([ |
| 1489 |
["Item:", item], |
| 1490 |
["Object:", received], |
| 1491 |
]), |
| 1492 |
})); |
| 1493 |
} |
| 1494 |
|
| 1495 |
/** |
| 1496 |
* Expects the received value to match the given `matcher`. |
| 1497 |
* |
| 1498 |
* @param {import("../hoot_utils").Matcher} matcher |
| 1499 |
* @param {ExpectOptions} [options] |
| 1500 |
* @example |
| 1501 |
* expect(new Error("foo")).toMatch("foo"); |
| 1502 |
* @example |
| 1503 |
* expect("a foo value").toMatch(/fo.*ue/); |
| 1504 |
*/ |
| 1505 |
toMatch(matcher, options) { |
| 1506 |
this._ensureArguments(arguments, "any"); |
| 1507 |
|
| 1508 |
return this._resolve(() => ({ |
| 1509 |
name: "toMatch", |
| 1510 |
acceptedType: "any", |
| 1511 |
predicate: (received) => match(received, matcher), |
| 1512 |
message: options?.message, |
| 1513 |
onPass: () => [this._received, r`[matches!does not match]`, matcher], |
| 1514 |
onFail: () => [r`expected value[! not] to match the given matcher`], |
| 1515 |
getFailedDetails: (received) => |
| 1516 |
detailsFromEntries([ |
| 1517 |
["Matcher:", matcher], |
| 1518 |
[null, received], |
| 1519 |
]), |
| 1520 |
})); |
| 1521 |
} |
| 1522 |
|
| 1523 |
/** |
| 1524 |
* Expects the received value to include the given object shape. |
| 1525 |
* |
| 1526 |
* A *partial* deep equality is performed, meaning that only the keys included |
| 1527 |
* in `partialObject` will be checked on the received value. |
| 1528 |
* |
| 1529 |
* This partial matching is only applied to non-iterable object, and not to |
| 1530 |
* arrays and other iterables; these are checked for deep equality. Although, |
| 1531 |
* non-iterable objects contained in iterables will be partially checked again. |
| 1532 |
* |
| 1533 |
* @param {Partial<R>} partialObject |
| 1534 |
* @param {ExpectOptions} [options] |
| 1535 |
* @example |
| 1536 |
* // Partial equality can be performed on nested objects |
| 1537 |
* expect({ |
| 1538 |
* company: { |
| 1539 |
* name: "Odoo", |
| 1540 |
* location: "Belgium", |
| 1541 |
* }, |
| 1542 |
* employees: new Set([ |
| 1543 |
* { |
| 1544 |
* name: "Julien", |
| 1545 |
* age: 28, |
| 1546 |
* }, |
| 1547 |
* ]), |
| 1548 |
* }).toMatchObject({ |
| 1549 |
* company: { name: "Odoo" } |
| 1550 |
* employees: new Set([{ age: 28 }]), |
| 1551 |
* }); |
| 1552 |
* @example |
| 1553 |
* // Iterables should have an (deep) equal content |
| 1554 |
* expect({ list: [1, 2, 3], other: "property" }).not.toMatchObject({ list: [1, 2] }); |
| 1555 |
* // ... as expected in the following assertion |
| 1556 |
* expect({ list: [1, 2, 3], other: "property" }).toMatchObject({ list: [1, 2, 3] }); |
| 1557 |
*/ |
| 1558 |
toMatchObject(partialObject, options) { |
| 1559 |
this._ensureArguments(arguments, "object"); |
| 1560 |
|
| 1561 |
return this._resolve(() => ({ |
| 1562 |
name: "toMatchObject", |
| 1563 |
acceptedType: ["object"], |
| 1564 |
predicate: (received) => deepEqual(received, partialObject, { partial: true }), |
| 1565 |
message: options?.message, |
| 1566 |
onPass: () => [this._received, r`[matches!does not match] object`, partialObject], |
| 1567 |
onFail: () => [r`expected object[! not] to match the given shape`], |
| 1568 |
getFailedDetails: (received) => |
| 1569 |
detailsFromEntries([ |
| 1570 |
["Partial object:", partialObject], |
| 1571 |
["Object:", received], |
| 1572 |
]), |
| 1573 |
})); |
| 1574 |
} |
| 1575 |
|
| 1576 |
/** |
| 1577 |
* Expects the received {@link Function} to throw an error after being called. |
| 1578 |
* |
| 1579 |
* @param {import("../hoot_utils").Matcher} [matcher=Error] |
| 1580 |
* @param {ExpectOptions} [options] |
| 1581 |
* @example |
| 1582 |
* expect(() => { throw new Error("Woops!") }).toThrow(/woops/i); |
| 1583 |
* @example |
| 1584 |
* await expect(Promise.reject("foo")).rejects.toThrow("foo"); |
| 1585 |
*/ |
| 1586 |
toThrow(matcher = Error, options) { |
| 1587 |
this._ensureArguments(arguments, "any"); |
| 1588 |
|
| 1589 |
return this._resolve(() => { |
| 1590 |
const isAsync = this._flags & (FLAGS.rejects | FLAGS.resolves); |
| 1591 |
let returnValue; |
| 1592 |
if (isAsync) { |
| 1593 |
returnValue = this._received; |
| 1594 |
} else { |
| 1595 |
try { |
| 1596 |
returnValue = this._received(); |
| 1597 |
} catch (error) { |
| 1598 |
returnValue = error; |
| 1599 |
} |
| 1600 |
} |
| 1601 |
return { |
| 1602 |
name: "toThrow", |
| 1603 |
acceptedType: ["function", "error"], |
| 1604 |
predicate: () => match(returnValue, matcher), |
| 1605 |
message: options?.message, |
| 1606 |
onPass: () => [ |
| 1607 |
this._received, |
| 1608 |
r`did[! not] ${isAsync ? "reject" : "throw"} a matching value`, |
| 1609 |
], |
| 1610 |
onFail: () => [ |
| 1611 |
this._received, |
| 1612 |
r`${ |
| 1613 |
isAsync ? "rejected" : "threw" |
| 1614 |
} a value that did not match the given matcher`, |
| 1615 |
], |
| 1616 |
getFailedDetails: () => |
| 1617 |
detailsFromEntries([ |
| 1618 |
["Matcher:", matcher], |
| 1619 |
[null, returnValue], |
| 1620 |
]), |
| 1621 |
}; |
| 1622 |
}); |
| 1623 |
} |
| 1624 |
|
| 1625 |
//------------------------------------------------------------------------- |
| 1626 |
// DOM matchers |
| 1627 |
//------------------------------------------------------------------------- |
| 1628 |
|
| 1629 |
/** |
| 1630 |
* Expects the received {@link Target} to be checked, or to be indeterminate |
| 1631 |
* if the homonymous option is set to `true`. |
| 1632 |
* |
| 1633 |
* @param {ExpectOptions & { indeterminate?: boolean }} [options] |
| 1634 |
* @example |
| 1635 |
* expect("input[type=checkbox]").toBeChecked(); |
| 1636 |
*/ |
| 1637 |
toBeChecked(options) { |
| 1638 |
this._ensureArguments(arguments); |
| 1639 |
|
| 1640 |
const prop = options?.indeterminate ? "indeterminate" : "checked"; |
| 1641 |
const pseudo = ":" + prop; |
| 1642 |
|
| 1643 |
return this._resolve(() => ({ |
| 1644 |
name: "toBeChecked", |
| 1645 |
acceptedType: ["string", "node", "node[]"], |
| 1646 |
mapElements: (el) => el.matches?.(pseudo), |
| 1647 |
predicate: (checked) => !!checked, |
| 1648 |
message: options?.message, |
| 1649 |
onPass: () => [this._received, r`[is%are][! not] ${prop}`], |
| 1650 |
onFail: () => [r`expected`, this._received, r`[! not] to be ${prop}`], |
| 1651 |
getFailedDetails: (checked) => detailsFromEntries([["Checked:", checked]]), |
| 1652 |
})); |
| 1653 |
} |
| 1654 |
|
| 1655 |
/** |
| 1656 |
* Expects the received {@link Target} to be displayed, meaning that: |
| 1657 |
* - it has a bounding box; |
| 1658 |
* - it is contained in the root document. |
| 1659 |
* |
| 1660 |
* @param {ExpectOptions} [options] |
| 1661 |
* @example |
| 1662 |
* expect(document.body).toBeDisplayed(); |
| 1663 |
* @example |
| 1664 |
* expect(document.createElement("div")).not.toBeDisplayed(); |
| 1665 |
*/ |
| 1666 |
toBeDisplayed(options) { |
| 1667 |
this._ensureArguments(arguments); |
| 1668 |
|
| 1669 |
return this._resolve(() => ({ |
| 1670 |
name: "toBeDisplayed", |
| 1671 |
acceptedType: ["string", "node", "node[]"], |
| 1672 |
mapElements: isNodeDisplayed, |
| 1673 |
predicate: (displayed) => !!displayed, |
| 1674 |
message: options?.message, |
| 1675 |
onPass: () => [this._received, r`[is%are][! not] displayed`], |
| 1676 |
onFail: () => [r`expected`, this._received, r`[! not] to be displayed`], |
| 1677 |
getFailedDetails: (displayed) => detailsFromEntries([["Displayed:", displayed]]), |
| 1678 |
})); |
| 1679 |
} |
| 1680 |
|
| 1681 |
/** |
| 1682 |
* Expects the received {@link Target} to be enabled, meaning that it |
| 1683 |
* matches the `:enabled` pseudo-selector. |
| 1684 |
* |
| 1685 |
* @param {ExpectOptions} [options] |
| 1686 |
* @example |
| 1687 |
* expect("button").toBeEnabled(); |
| 1688 |
* @example |
| 1689 |
* expect("input[type=radio]").not.toBeEnabled(); |
| 1690 |
*/ |
| 1691 |
toBeEnabled(options) { |
| 1692 |
this._ensureArguments(arguments); |
| 1693 |
|
| 1694 |
return this._resolve(() => ({ |
| 1695 |
name: "toBeEnabled", |
| 1696 |
acceptedType: ["string", "node", "node[]"], |
| 1697 |
mapElements: (el) => el.matches?.(":enabled"), |
| 1698 |
predicate: (enabled) => !!enabled, |
| 1699 |
message: options?.message, |
| 1700 |
onPass: () => [this._received, r`[is%are] [enabled!disabled]`], |
| 1701 |
onFail: () => [r`expected`, this._received, r`to be [enabled!disabled]`], |
| 1702 |
getFailedDetails: (enabled) => detailsFromEntries([["Enabled:", enabled]]), |
| 1703 |
})); |
| 1704 |
} |
| 1705 |
|
| 1706 |
/** |
| 1707 |
* Expects the received {@link Target} to be focused in its owner document. |
| 1708 |
* |
| 1709 |
* @param {ExpectOptions} [options] |
| 1710 |
*/ |
| 1711 |
toBeFocused(options) { |
| 1712 |
this._ensureArguments(arguments); |
| 1713 |
|
| 1714 |
return this._resolve(() => ({ |
| 1715 |
name: "toBeFocused", |
| 1716 |
acceptedType: ["string", "node", "node[]"], |
| 1717 |
mapElements: (el) => getActiveElement(el), |
| 1718 |
predicate: (activeEl, el) => strictEqual(el, activeEl), |
| 1719 |
message: options?.message, |
| 1720 |
onPass: () => [this._received, r`[is%are][! not] focused`], |
| 1721 |
onFail: () => [this._received, r`should[! not] be focused`], |
| 1722 |
getFailedDetails: (focused) => detailsFromEntries([["Focused:", focused]]), |
| 1723 |
})); |
| 1724 |
} |
| 1725 |
|
| 1726 |
/** |
| 1727 |
* Expects the received {@link Target} to be visible, meaning that: |
| 1728 |
* - it has a bounding box; |
| 1729 |
* - it is contained in the root document; |
| 1730 |
* - it is not hidden by CSS properties. |
| 1731 |
* |
| 1732 |
* @param {ExpectOptions} [options] |
| 1733 |
* @example |
| 1734 |
* expect(document.body).toBeVisible(); |
| 1735 |
* @example |
| 1736 |
* expect("[style='opacity: 0']").not.toBeVisible(); |
| 1737 |
*/ |
| 1738 |
toBeVisible(options) { |
| 1739 |
this._ensureArguments(arguments); |
| 1740 |
|
| 1741 |
return this._resolve(() => ({ |
| 1742 |
name: "toBeVisible", |
| 1743 |
acceptedType: ["string", "node", "node[]"], |
| 1744 |
mapElements: isNodeVisible, |
| 1745 |
predicate: (visible) => !!visible, |
| 1746 |
message: options?.message, |
| 1747 |
onPass: () => [this._received, r`[is%are] [visible!hidden]`], |
| 1748 |
onFail: () => [r`expected`, this._received, r`to be [visible!hidden]`], |
| 1749 |
getFailedDetails: (visible) => detailsFromEntries([["Visible:", visible]]), |
| 1750 |
})); |
| 1751 |
} |
| 1752 |
|
| 1753 |
/** |
| 1754 |
* Expects the received {@link Target} to have the given attribute set on |
| 1755 |
* itself, and for that attribute value to match the given `value` if any. |
| 1756 |
* |
| 1757 |
* @param {string} attribute |
| 1758 |
* @param {import("../hoot_utils").Matcher} [value] |
| 1759 |
* @param {ExpectOptions} [options] |
| 1760 |
* @example |
| 1761 |
* expect("a").toHaveAttribute("href"); |
| 1762 |
* @example |
| 1763 |
* expect("script").toHaveAttribute("src", "./index.js"); |
| 1764 |
*/ |
| 1765 |
toHaveAttribute(attribute, value, options) { |
| 1766 |
this._ensureArguments(arguments, "string", ["string", "number", "regex", null]); |
| 1767 |
|
| 1768 |
const expectsValue = !isNil(value); |
| 1769 |
|
| 1770 |
return this._resolve(() => ({ |
| 1771 |
name: "toHaveAttribute", |
| 1772 |
acceptedType: ["string", "node", "node[]"], |
| 1773 |
mapElements: (el) => getNodeAttribute(el, attribute), |
| 1774 |
predicate: (elAttr, el) => |
| 1775 |
expectsValue ? valueMatches(elAttr, value) : el.hasAttribute(attribute), |
| 1776 |
message: options?.message, |
| 1777 |
onPass: () => [ |
| 1778 |
r`attribute`, |
| 1779 |
attribute, |
| 1780 |
r`on`, |
| 1781 |
this._received, |
| 1782 |
...(expectsValue ? [r`[matches!does not match]`, value] : [r`is[! not] set`]), |
| 1783 |
], |
| 1784 |
onFail: () => [ |
| 1785 |
this._received, |
| 1786 |
r`[does%do] not have the correct attribute${expectsValue ? " value" : ""}`, |
| 1787 |
], |
| 1788 |
getFailedDetails: (elAttr) => |
| 1789 |
detailsFromValuesWithDiff(expectsValue ? value : attribute, elAttr), |
| 1790 |
})); |
| 1791 |
} |
| 1792 |
|
| 1793 |
/** |
| 1794 |
* Expects the received {@link Target} to have the given class name(s). |
| 1795 |
* |
| 1796 |
* @param {string | string[]} className |
| 1797 |
* @param {ExpectOptions & ClassListOptions} [options] |
| 1798 |
* @example |
| 1799 |
* expect("inline").toHaveClass("btn btn-primary"); |
| 1800 |
* @example |
| 1801 |
* expect("body").toHaveClass(["o_webclient", "o_dark"]); |
| 1802 |
*/ |
| 1803 |
toHaveClass(className, options) { |
| 1804 |
this._ensureArguments(arguments, ["string", "string[]"]); |
| 1805 |
|
| 1806 |
const rawClassNames = ensureArray(className); |
| 1807 |
const classNames = rawClassNames.flatMap((cls) => cls.trim().split(R_WHITE_SPACE)); |
| 1808 |
|
| 1809 |
return this._resolve(() => ({ |
| 1810 |
name: "toHaveClass", |
| 1811 |
acceptedType: ["string", "node", "node[]"], |
| 1812 |
mapElements: (el) => [...el.classList].sort(), |
| 1813 |
predicate: (classes) => |
| 1814 |
options?.exact |
| 1815 |
? deepEqual(classNames, classes, { ignoreOrder: true }) |
| 1816 |
: classNames.every((cls) => classes.includes(cls)), |
| 1817 |
message: options?.message, |
| 1818 |
onPass: () => [ |
| 1819 |
this._received, |
| 1820 |
r`[[has%have]![does%do] not have] class${classNames.length === 1 ? "" : "es"}`, |
| 1821 |
...listJoin(classNames, ",", "and"), |
| 1822 |
], |
| 1823 |
onFail: () => [ |
| 1824 |
r`expected`, |
| 1825 |
this._received, |
| 1826 |
r`[to have all!not to have any] of the given class names`, |
| 1827 |
], |
| 1828 |
getFailedDetails: (classes) => |
| 1829 |
detailsFromValues(classNames.join(" "), classes.join(" ")), |
| 1830 |
})); |
| 1831 |
} |
| 1832 |
|
| 1833 |
/** |
| 1834 |
* Expects the received {@link Target} to contain exactly `amount` element(s). |
| 1835 |
* Note that the `amount` parameter can be omitted, in which case the function |
| 1836 |
* will expect *at least* one element. |
| 1837 |
* |
| 1838 |
* @param {number} [amount] |
| 1839 |
* @param {ExpectOptions} [options] |
| 1840 |
* @example |
| 1841 |
* expect(".o_webclient").toHaveCount(1); |
| 1842 |
* @example |
| 1843 |
* expect(".o_form_view .o_field_widget").toHaveCount(); |
| 1844 |
* @example |
| 1845 |
* expect("ul > li").toHaveCount(4); |
| 1846 |
*/ |
| 1847 |
toHaveCount(amount, options) { |
| 1848 |
this._ensureArguments(arguments, ["integer", null]); |
| 1849 |
|
| 1850 |
const anyAmount = isNil(amount); |
| 1851 |
return this._resolve(() => { |
| 1852 |
const elMap = new ElementMap(this._received); |
| 1853 |
return { |
| 1854 |
name: "toHaveCount", |
| 1855 |
acceptedType: ["string", "node", "node[]"], |
| 1856 |
predicate: () => (anyAmount ? elMap.size > 0 : strictEqual(elMap.size, amount)), |
| 1857 |
message: options?.message, |
| 1858 |
onPass: () => [r`found`, elMap], |
| 1859 |
onFail: () => [ |
| 1860 |
r`found`, |
| 1861 |
elMap, |
| 1862 |
...(anyAmount ? [r`and expected [any amount!none]`] : []), |
| 1863 |
], |
| 1864 |
getFailedDetails: () => [ |
| 1865 |
...detailsFromValues( |
| 1866 |
anyAmount ? (this._flags & FLAGS.not ? S_NONE : S_ANY) : amount, |
| 1867 |
elMap.size |
| 1868 |
), |
| 1869 |
Markup.text("Elements:", [...elMap.keys()]), |
| 1870 |
], |
| 1871 |
}; |
| 1872 |
}); |
| 1873 |
} |
| 1874 |
|
| 1875 |
/** |
| 1876 |
* Expects the `innerHTML` of the received {@link Target} to match the `expected` |
| 1877 |
* value (upon formatting). |
| 1878 |
* |
| 1879 |
* @param {string | RegExp} [expected] |
| 1880 |
* @param {ExpectOptions & FormatXmlOptions} [options] |
| 1881 |
* @example |
| 1882 |
* expect(".my_element").toHaveInnerHTML(` |
| 1883 |
* Some <strong>text</strong> |
| 1884 |
* `); |
| 1885 |
*/ |
| 1886 |
toHaveInnerHTML(expected, options) { |
| 1887 |
this._ensureArguments(arguments, ["string", "regex"]); |
| 1888 |
|
| 1889 |
return this._toHaveHTML("toHaveInnerHTML", "innerHTML", ...arguments); |
| 1890 |
} |
| 1891 |
|
| 1892 |
/** |
| 1893 |
* Expects the `outerHTML` of the received {@link Target} to match the `expected` |
| 1894 |
* value (upon formatting). |
| 1895 |
* |
| 1896 |
* @param {string | RegExp} [expected] |
| 1897 |
* @param {ExpectOptions & FormatXmlOptions} [options] |
| 1898 |
* @example |
| 1899 |
* expect(".my_element").toHaveOuterHTML(` |
| 1900 |
* <div class="my_element"> |
| 1901 |
* Some <strong>text</strong> |
| 1902 |
* </div> |
| 1903 |
* `); |
| 1904 |
*/ |
| 1905 |
toHaveOuterHTML(expected, options) { |
| 1906 |
this._ensureArguments(arguments, ["string", "regex"]); |
| 1907 |
|
| 1908 |
return this._toHaveHTML("toHaveOuterHTML", "outerHTML", ...arguments); |
| 1909 |
} |
| 1910 |
|
| 1911 |
/** |
| 1912 |
* Expects the received {@link Target} to have its given property value match |
| 1913 |
* the given `value`. |
| 1914 |
* |
| 1915 |
* @param {string} property |
| 1916 |
* @param {any} [value] |
| 1917 |
* @param {ExpectOptions} [options] |
| 1918 |
* @example |
| 1919 |
* expect("button").toHaveProperty("tabIndex", 0); |
| 1920 |
* @example |
| 1921 |
* expect("script").toHaveProperty("src", "./index.js"); |
| 1922 |
*/ |
| 1923 |
toHaveProperty(property, value, options) { |
| 1924 |
this._ensureArguments(arguments, "string", "any"); |
| 1925 |
|
| 1926 |
const expectsValue = !isNil(value); |
| 1927 |
return this._resolve(() => ({ |
| 1928 |
name: "toHaveProperty", |
| 1929 |
acceptedType: ["string", "node", "node[]"], |
| 1930 |
mapElements: (el) => el[property], |
| 1931 |
predicate: (elProp, el) => |
| 1932 |
expectsValue ? valueMatches(elProp, value) : property in el, |
| 1933 |
message: options?.message, |
| 1934 |
onPass: () => [ |
| 1935 |
r`property`, |
| 1936 |
property, |
| 1937 |
r`on`, |
| 1938 |
this._received, |
| 1939 |
...(expectsValue ? [r`[matches!does not match]`, value] : [r`is[! not] set`]), |
| 1940 |
], |
| 1941 |
onFail: () => [ |
| 1942 |
this._received, |
| 1943 |
r`[does%do] not have the correct property${expectsValue ? " value" : ""}`, |
| 1944 |
], |
| 1945 |
getFailedDetails: (elProp) => |
| 1946 |
detailsFromValuesWithDiff(expectsValue ? value : property, elProp), |
| 1947 |
})); |
| 1948 |
} |
| 1949 |
|
| 1950 |
/** |
| 1951 |
* Expects the {@link DOMRect} of the received {@link Target} to match the given |
| 1952 |
* `rect` object. |
| 1953 |
* |
| 1954 |
* The `rect` object can either be: |
| 1955 |
* - a {@link DOMRect} object; |
| 1956 |
* - a CSS selector string (to get the rect of the *only* matching element); |
| 1957 |
* - a node. |
| 1958 |
* |
| 1959 |
* If the resulting `rect` value is a node, then both nodes' rects will be compared. |
| 1960 |
* |
| 1961 |
* @param {Partial<DOMRect> | Target} rect |
| 1962 |
* @param {ExpectOptions & QueryRectOptions} [options] |
| 1963 |
* @example |
| 1964 |
* expect("button").toHaveRect({ x: 20, width: 100, height: 50 }); |
| 1965 |
* @example |
| 1966 |
* expect("button").toHaveRect(".container"); |
| 1967 |
*/ |
| 1968 |
toHaveRect(rect, options) { |
| 1969 |
this._ensureArguments(arguments, ["object", "string", "node", "node[]"]); |
| 1970 |
|
| 1971 |
let refRect; |
| 1972 |
if (typeof rect === "string" || isNode(rect)) { |
| 1973 |
refRect = { ...queryRect(rect, options) }; |
| 1974 |
} else { |
| 1975 |
refRect = rect; |
| 1976 |
} |
| 1977 |
|
| 1978 |
const entries = $entries(refRect); |
| 1979 |
|
| 1980 |
return this._resolve(() => ({ |
| 1981 |
name: "toHaveRect", |
| 1982 |
acceptedType: ["string", "node", "node[]"], |
| 1983 |
mapElements: (el) => getNodeRect(el, options), |
| 1984 |
predicate: (elRect) => entries.every(([key, val]) => strictEqual(elRect[key], val)), |
| 1985 |
message: options?.message, |
| 1986 |
onPass: () => [this._received, r`[has%have] the expected DOM rect of`, rect], |
| 1987 |
onFail: () => [r`expected`, this._received, r`to have the given DOM rect`], |
| 1988 |
getFailedDetails: (elRect) => detailsFromValuesWithDiff(rect, elRect), |
| 1989 |
})); |
| 1990 |
} |
| 1991 |
|
| 1992 |
/** |
| 1993 |
* Expects the received {@link Target} to match the given style properties. |
| 1994 |
* |
| 1995 |
* @param {string | Record<string, string | RegExp>} style |
| 1996 |
* @param {ExpectOptions & DOMStyleOptions} [options] |
| 1997 |
* @example |
| 1998 |
* expect("button").toHaveStyle({ color: "red" }); |
| 1999 |
* @example |
| 2000 |
* expect("p").toHaveStyle("text-align: center"); |
| 2001 |
*/ |
| 2002 |
toHaveStyle(style, options) { |
| 2003 |
this._ensureArguments(arguments, ["string", "object"]); |
| 2004 |
|
| 2005 |
const styleDef = parseInlineStyle(style, S_ANY); |
| 2006 |
const styleKeys = $keys(styleDef); |
| 2007 |
|
| 2008 |
return this._resolve(() => ({ |
| 2009 |
name: "toHaveStyle", |
| 2010 |
acceptedType: ["string", "node", "node[]"], |
| 2011 |
mapElements: (el) => |
| 2012 |
options?.inline |
| 2013 |
? parseInlineStyle(el.getAttribute("style")) |
| 2014 |
: getStyleValues(el, $keys(styleDef)), |
| 2015 |
predicate: (elStyle) => |
| 2016 |
styleKeys.every((key) => valueMatches(elStyle[key], styleDef[key])) && |
| 2017 |
(!options?.exact || deepEqual(styleKeys, $keys(elStyle), { ignoreOrder: true })), |
| 2018 |
message: options?.message, |
| 2019 |
onPass: () => [ |
| 2020 |
this._received, |
| 2021 |
r`[has%have] the expected style values for`, |
| 2022 |
...listJoin($keys(styleDef), ",", "and"), |
| 2023 |
], |
| 2024 |
onFail: () => [ |
| 2025 |
r`expected`, |
| 2026 |
this._received, |
| 2027 |
r`[to have all!not to have any] of the given style properties`, |
| 2028 |
], |
| 2029 |
getFailedDetails: (elStyle) => detailsFromValuesWithDiff(styleDef, elStyle), |
| 2030 |
})); |
| 2031 |
} |
| 2032 |
|
| 2033 |
/** |
| 2034 |
* Expects the text content of the received {@link Target} to either: |
| 2035 |
* - be strictly equal to a given string; |
| 2036 |
* - match a given regular expression. |
| 2037 |
* |
| 2038 |
* @param {string | RegExp} [text] |
| 2039 |
* @param {ExpectOptions & QueryTextOptions} [options] |
| 2040 |
* @example |
| 2041 |
* expect("p").toHaveText("lorem ipsum dolor sit amet"); |
| 2042 |
* @example |
| 2043 |
* expect("header h1").toHaveText(/odoo/i); |
| 2044 |
*/ |
| 2045 |
toHaveText(text, options) { |
| 2046 |
this._ensureArguments(arguments, ["string", "regex", null]); |
| 2047 |
|
| 2048 |
const expectsText = !isNil(text); |
| 2049 |
|
| 2050 |
return this._resolve(() => ({ |
| 2051 |
name: "toHaveText", |
| 2052 |
acceptedType: ["string", "node", "node[]"], |
| 2053 |
mapElements: (el) => getNodeText(el, options), |
| 2054 |
predicate: (elText) => (expectsText ? valueMatches(elText, text) : elText.length > 0), |
| 2055 |
message: options?.message, |
| 2056 |
onPass: () => [this._received, r`[[has%have]![does%do] not have] text`, text], |
| 2057 |
onFail: () => [r`expected`, this._received, r`[! not] to have the given text`], |
| 2058 |
getFailedDetails: (elText) => detailsFromValuesWithDiff(text, elText), |
| 2059 |
})); |
| 2060 |
} |
| 2061 |
|
| 2062 |
/** |
| 2063 |
* Expects the value of the received {@link Target} to either: |
| 2064 |
* - be strictly equal to a given string or number; |
| 2065 |
* - match a given regular expression; |
| 2066 |
* - contain file objects matching the given `files` list. |
| 2067 |
* |
| 2068 |
* @param {ReturnType<typeof getNodeValue>} [value] |
| 2069 |
* @param {ExpectOptions & { raw?: boolean }} [options] |
| 2070 |
* @example |
| 2071 |
* expect("input[name=age]").toHaveValue(29); |
| 2072 |
* @example |
| 2073 |
* expect("input[type=file]").toHaveValue(new File(["foo"], "foo.txt")); |
| 2074 |
* @example |
| 2075 |
* expect("select[multiple]").toHaveValue(["foo", "bar"]); |
| 2076 |
* @example |
| 2077 |
* expect("input[name=age]").toHaveValue("29", { raw: true }); |
| 2078 |
*/ |
| 2079 |
toHaveValue(value, options) { |
| 2080 |
this._ensureArguments(arguments, [ |
| 2081 |
"string", |
| 2082 |
"string[]", |
| 2083 |
"number", |
| 2084 |
"object[]", |
| 2085 |
"regex", |
| 2086 |
null, |
| 2087 |
]); |
| 2088 |
|
| 2089 |
const expectsValue = !isNil(value); |
| 2090 |
|
| 2091 |
return this._resolve(() => ({ |
| 2092 |
name: "toHaveValue", |
| 2093 |
acceptedType: ["string", "node", "node[]"], |
| 2094 |
mapElements: (el) => getNodeValue(el, options?.raw), |
| 2095 |
predicate: (elValue, el) => { |
| 2096 |
if (isCheckable(el)) { |
| 2097 |
throw new HootError( |
| 2098 |
`cannot call \`toHaveValue()\` on a checkbox or radio input: use \`toBeChecked()\` instead` |
| 2099 |
); |
| 2100 |
} |
| 2101 |
if (!expectsValue) { |
| 2102 |
return isIterable(elValue) ? [...elValue].length > 0 : el.value !== ""; |
| 2103 |
} |
| 2104 |
if (isIterable(elValue)) { |
| 2105 |
if (isIterable(value)) { |
| 2106 |
return deepEqual(elValue, value); |
| 2107 |
} |
| 2108 |
elValue = el.value; |
| 2109 |
} |
| 2110 |
return valueMatches(elValue, value); |
| 2111 |
}, |
| 2112 |
message: options?.message, |
| 2113 |
onPass: () => [this._received, r`[[has%have]![does%do] not have] value`, value], |
| 2114 |
onFail: () => [r`expected`, this._received, r`[! not] to have the given value`], |
| 2115 |
getFailedDetails: (elValue) => detailsFromValuesWithDiff(value, elValue), |
| 2116 |
})); |
| 2117 |
} |
| 2118 |
|
| 2119 |
//------------------------------------------------------------------------- |
| 2120 |
// Private methods |
| 2121 |
//------------------------------------------------------------------------- |
| 2122 |
|
| 2123 |
/** |
| 2124 |
* @private |
| 2125 |
* @param {number} flags |
| 2126 |
*/ |
| 2127 |
_clone(flags) { |
| 2128 |
unconsumedMatchers.delete(this); |
| 2129 |
return new this.constructor(this._result, this._received, this._flags | flags); |
| 2130 |
} |
| 2131 |
|
| 2132 |
/** |
| 2133 |
* Validates the given `arguments` object, with an implicitly added `options` |
| 2134 |
* validator at the end (optional). |
| 2135 |
* |
| 2136 |
* Flags are then modified based on these options, and the current stack is |
| 2137 |
* saved for error reporting. |
| 2138 |
* |
| 2139 |
* @private |
| 2140 |
* @param {any[]} argumentsObject |
| 2141 |
* @param {...(ArgumentType | ArgumentType[])} argumentsDefs |
| 2142 |
*/ |
| 2143 |
_ensureArguments(argumentsObject, ...argumentsDefs) { |
| 2144 |
if (!unconsumedMatchers.has(this)) { |
| 2145 |
throw new HootError(`cannot use multiple matchers on the same \`expect()\` call`); |
| 2146 |
} |
| 2147 |
unconsumedMatchers.delete(this); |
| 2148 |
|
| 2149 |
const args = [...argumentsObject]; |
| 2150 |
ensureArguments(args, ...argumentsDefs, ["object", null]); |
| 2151 |
|
| 2152 |
const options = args[argumentsDefs.length] || {}; |
| 2153 |
for (const flag in FLAGS) { |
| 2154 |
if (flag in options) { |
| 2155 |
if (options[flag]) { |
| 2156 |
this._flags |= FLAGS[flag]; |
| 2157 |
} else { |
| 2158 |
this._flags &= ~FLAGS[flag]; |
| 2159 |
} |
| 2160 |
} |
| 2161 |
} |
| 2162 |
|
| 2163 |
if (!(this._flags & FLAGS.headless)) { |
| 2164 |
currentStack = getStack(1); |
| 2165 |
} |
| 2166 |
} |
| 2167 |
|
| 2168 |
/** |
| 2169 |
* @private |
| 2170 |
* @param {() => MatcherSpecifications<R, A>} specCallback |
| 2171 |
* @returns {Async extends true ? Promise<boolean> : boolean} |
| 2172 |
*/ |
| 2173 |
_resolve(specCallback) { |
| 2174 |
const isAsync = this._flags & (FLAGS.rejects | FLAGS.resolves); |
| 2175 |
if (this._flags & FLAGS.error) { |
| 2176 |
// Prevent further assertions in error state |
| 2177 |
return isAsync ? new Promise(() => {}) : undefined; |
| 2178 |
} |
| 2179 |
if (isAsync) { |
| 2180 |
return Promise.resolve(this._received).then( |
| 2181 |
/** @param {PromiseFulfilledResult<R>} reason */ |
| 2182 |
(result) => { |
| 2183 |
if (this._flags & FLAGS.rejects) { |
| 2184 |
this._result.registerEvent("assertion", { |
| 2185 |
label: "rejects", |
| 2186 |
pass: false, |
| 2187 |
reportMessage: [ |
| 2188 |
r`expected promise to reject, instead resolved with:`, |
| 2189 |
result, |
| 2190 |
], |
| 2191 |
}); |
| 2192 |
return false; |
| 2193 |
} else { |
| 2194 |
this._received = result; |
| 2195 |
return this._resolveFinalResult(specCallback); |
| 2196 |
} |
| 2197 |
}, |
| 2198 |
/** @param {PromiseRejectedResult} reason */ |
| 2199 |
(reason) => { |
| 2200 |
if (this._flags & FLAGS.resolves) { |
| 2201 |
this._result.registerEvent("assertion", { |
| 2202 |
label: "resolves", |
| 2203 |
pass: false, |
| 2204 |
reportMessage: [ |
| 2205 |
r`expected promise to resolve, instead rejected with:`, |
| 2206 |
reason, |
| 2207 |
], |
| 2208 |
}); |
| 2209 |
return false; |
| 2210 |
} else { |
| 2211 |
this._received = reason; |
| 2212 |
return this._resolveFinalResult(specCallback); |
| 2213 |
} |
| 2214 |
} |
| 2215 |
); |
| 2216 |
} else { |
| 2217 |
return this._resolveFinalResult(specCallback); |
| 2218 |
} |
| 2219 |
} |
| 2220 |
|
| 2221 |
/** |
| 2222 |
* @private |
| 2223 |
* @param {() => MatcherSpecifications<R, A>} specCallback |
| 2224 |
* @returns {boolean} |
| 2225 |
*/ |
| 2226 |
_resolveFinalResult(specCallback) { |
| 2227 |
let { |
| 2228 |
acceptedType, |
| 2229 |
getFailedDetails, |
| 2230 |
mapElements, |
| 2231 |
message, |
| 2232 |
name, |
| 2233 |
onFail, |
| 2234 |
onPass, |
| 2235 |
predicate, |
| 2236 |
} = specCallback(); |
| 2237 |
|
| 2238 |
const types = ensureArray(acceptedType); |
| 2239 |
if (!types.some((type) => isOfType(this._received, type))) { |
| 2240 |
const joinedTypes = |
| 2241 |
types.length > 1 |
| 2242 |
? new ListFormat("en-GB", { |
| 2243 |
type: "disjunction", |
| 2244 |
style: "long", |
| 2245 |
}).format(types) |
| 2246 |
: types[0]; |
| 2247 |
throw new TypeError( |
| 2248 |
`expected received value to be of type ${joinedTypes}, got ${formatHumanReadable( |
| 2249 |
this._received |
| 2250 |
)}` |
| 2251 |
); |
| 2252 |
} |
| 2253 |
|
| 2254 |
if (mapElements) { |
| 2255 |
this._received = new ElementMap(this._received, mapElements); |
| 2256 |
} |
| 2257 |
function passPredicate(...args) { |
| 2258 |
return not ? !predicate(...args) : predicate(...args); |
| 2259 |
} |
| 2260 |
const not = this._flags & FLAGS.not; |
| 2261 |
let pass; |
| 2262 |
if (mapElements) { |
| 2263 |
pass = this._received.every(passPredicate); |
| 2264 |
if (!pass && !this._received.size) { |
| 2265 |
onFail = [r`expected at least`, 1, r`element and got`, this._received]; |
| 2266 |
} |
| 2267 |
} else { |
| 2268 |
pass = passPredicate(this._received); |
| 2269 |
} |
| 2270 |
|
| 2271 |
if (!(this._flags & FLAGS.silent)) { |
| 2272 |
const assertion = { |
| 2273 |
flags: this._flags, |
| 2274 |
label: name, |
| 2275 |
message, |
| 2276 |
pass, |
| 2277 |
reportMessage: pass ? onPass : onFail, |
| 2278 |
}; |
| 2279 |
if (!pass) { |
| 2280 |
if (mapElements) { |
| 2281 |
assertion.failedDetails = this._received.mapFailedDetails( |
| 2282 |
getFailedDetails, |
| 2283 |
passPredicate |
| 2284 |
); |
| 2285 |
} else { |
| 2286 |
assertion.failedDetails = getFailedDetails(this._received); |
| 2287 |
} |
| 2288 |
assertion.stack = currentStack; |
| 2289 |
} |
| 2290 |
this._result.registerEvent("assertion", assertion); |
| 2291 |
} |
| 2292 |
|
| 2293 |
return pass; |
| 2294 |
} |
| 2295 |
|
| 2296 |
/** |
| 2297 |
* @private |
| 2298 |
* @param {"toHaveInnerHTML" | "toHaveOuterHTML"} name |
| 2299 |
* @param {"innerHTML" | "outerHTML"} property |
| 2300 |
* @param {string | RegExp} expected |
| 2301 |
* @param {ExpectOptions & FormatXmlOptions} [options] |
| 2302 |
*/ |
| 2303 |
_toHaveHTML(name, property, expected, options) { |
| 2304 |
options = { type: "html", ...options }; |
| 2305 |
if (!isInstanceOf(expected, RegExp)) { |
| 2306 |
expected = formatXml(expected, options); |
| 2307 |
} |
| 2308 |
|
| 2309 |
return this._resolve(() => ({ |
| 2310 |
name, |
| 2311 |
acceptedType: ["string", "node", "node[]"], |
| 2312 |
mapElements: (el) => |
| 2313 |
// Force HTML type here as it will be returned by outer/inner HTML |
| 2314 |
formatXml(el[property], { ...options, type: "html" }), |
| 2315 |
predicate: (elHtml) => valueMatches(elHtml, expected), |
| 2316 |
message: options?.message, |
| 2317 |
onPass: () => [property, r`of`, this._received, r`is[! not] equal to expected value`], |
| 2318 |
onFail: () => [ |
| 2319 |
r`expected`, |
| 2320 |
property, |
| 2321 |
r`of`, |
| 2322 |
this._received, |
| 2323 |
r`to match the given value`, |
| 2324 |
], |
| 2325 |
getFailedDetails: (val) => detailsFromValuesWithDiff(expected, val), |
| 2326 |
})); |
| 2327 |
} |
| 2328 |
} |
| 2329 |
|
| 2330 |
//----------------------------------------------------------------------------- |
| 2331 |
// Case events |
| 2332 |
//----------------------------------------------------------------------------- |
| 2333 |
|
| 2334 |
export class CaseEvent { |
| 2335 |
label = ""; |
| 2336 |
/** @type {(string | Label)[]} */ |
| 2337 |
message = []; |
| 2338 |
ts = $floor($now()); |
| 2339 |
/** @type {number} */ |
| 2340 |
type; |
| 2341 |
} |
| 2342 |
|
| 2343 |
export class Assertion extends CaseEvent { |
| 2344 |
/** @type {string | null | undefined} */ |
| 2345 |
additionalMessage; |
| 2346 |
/** @type {string | undefined} */ |
| 2347 |
docLabel; |
| 2348 |
type = CASE_EVENT_TYPES.assertion.value; |
| 2349 |
|
| 2350 |
/** |
| 2351 |
* @param {number} number |
| 2352 |
* @param {Partial<Assertion & { |
| 2353 |
* docLabel?: string; |
| 2354 |
* message: AssertionMessage, |
| 2355 |
* reportMessage: AssertionReportMessage, |
| 2356 |
* }>} values |
| 2357 |
*/ |
| 2358 |
constructor(number, values) { |
| 2359 |
super(); |
| 2360 |
|
| 2361 |
this.docLabel = values.docLabel; |
| 2362 |
this.label = values.label; |
| 2363 |
this.flags = values.flags || 0; |
| 2364 |
this.pass = values.pass || false; |
| 2365 |
this.number = number; |
| 2366 |
|
| 2367 |
if (!this.pass) { |
| 2368 |
/** @type {[any, any][] | null} */ |
| 2369 |
this.failedDetails = Markup.resolveDetails(values.failedDetails || []); |
| 2370 |
/** @type {string} */ |
| 2371 |
this.stack = values.stack; |
| 2372 |
} |
| 2373 |
|
| 2374 |
let { message, reportMessage } = values; |
| 2375 |
|
| 2376 |
// Message |
| 2377 |
if (typeof message === "function") { |
| 2378 |
this.additionalMessage = message(); |
| 2379 |
} else { |
| 2380 |
this.additionalMessage = message; |
| 2381 |
} |
| 2382 |
|
| 2383 |
// Reporting message |
| 2384 |
if (typeof reportMessage === "function") { |
| 2385 |
reportMessage = reportMessage(this.pass, r); |
| 2386 |
} |
| 2387 |
const parts = |
| 2388 |
$isArray(reportMessage) && !isLabel(reportMessage) |
| 2389 |
? reportMessage |
| 2390 |
: [makeLabel(reportMessage, null)]; |
| 2391 |
const plural = parts.some((p) => p instanceof ElementMap && p.size !== 1); |
| 2392 |
const not = this.flags & FLAGS.not; |
| 2393 |
for (const part of parts) { |
| 2394 |
if (part instanceof ElementMap) { |
| 2395 |
const subject = part.size === 1 ? "element" : "elements"; |
| 2396 |
if (part.selector) { |
| 2397 |
this.message.push( |
| 2398 |
makeLabelOrString(part.size), |
| 2399 |
`${subject} matching`, |
| 2400 |
makeLabelOrString(part.selector) |
| 2401 |
); |
| 2402 |
} else { |
| 2403 |
const elements = part.keys(); |
| 2404 |
this.message.push( |
| 2405 |
subject, |
| 2406 |
makeLabelOrString(part.size === 1 ? elements.next().value : [...elements]) |
| 2407 |
); |
| 2408 |
} |
| 2409 |
} else if (isLabel(part)) { |
| 2410 |
if (part[1] === "icon") { |
| 2411 |
this.message.push(part); |
| 2412 |
} else { |
| 2413 |
this.message.push( |
| 2414 |
makeLabelOrString(formatMessage(part[0], plural, not), part[1]) |
| 2415 |
); |
| 2416 |
} |
| 2417 |
} else if (typeof part === "string") { |
| 2418 |
this.message.push(makeLabelOrString(formatMessage(part, plural, not))); |
| 2419 |
} else { |
| 2420 |
this.message.push(makeLabelOrString(part)); |
| 2421 |
} |
| 2422 |
} |
| 2423 |
} |
| 2424 |
|
| 2425 |
/** |
| 2426 |
* @param {keyof typeof FLAGS} name |
| 2427 |
*/ |
| 2428 |
hasFlag(name) { |
| 2429 |
return this.flags & FLAGS[name]; |
| 2430 |
} |
| 2431 |
} |
| 2432 |
|
| 2433 |
export class DOMCaseEvent extends CaseEvent { |
| 2434 |
/** |
| 2435 |
* @param {InteractionType} type |
| 2436 |
* @param {InteractionDetails} details |
| 2437 |
*/ |
| 2438 |
constructor(type, [name, alias, args, returnValue]) { |
| 2439 |
super(); |
| 2440 |
|
| 2441 |
this.type = CASE_EVENT_TYPES[type].value; |
| 2442 |
this.label = alias || name; |
| 2443 |
if (type === "server") { |
| 2444 |
this.docLabel = mockFetch.name; |
| 2445 |
} else { |
| 2446 |
this.docLabel = name; |
| 2447 |
} |
| 2448 |
for (let i = 0; i < args.length; i++) { |
| 2449 |
if (args[i] !== undefined && (i === 0 || typeof args[i] !== "object")) { |
| 2450 |
this.message.push(makeLabelOrString(args[i])); |
| 2451 |
} |
| 2452 |
} |
| 2453 |
if (returnValue && type === "query" && returnValue !== args[0]) { |
| 2454 |
this.message.push(ARROW_RIGHT, makeLabelOrString(returnValue)); |
| 2455 |
} |
| 2456 |
} |
| 2457 |
} |
| 2458 |
|
| 2459 |
export class CaseError extends CaseEvent { |
| 2460 |
type = CASE_EVENT_TYPES.error.value; |
| 2461 |
|
| 2462 |
/** |
| 2463 |
* @param {Error} error |
| 2464 |
*/ |
| 2465 |
constructor(error) { |
| 2466 |
super(); |
| 2467 |
|
| 2468 |
/** @type {Error | null} */ |
| 2469 |
this.cause = error.cause || null; |
| 2470 |
this.label = error.name; |
| 2471 |
this.message = error.message.split(R_WHITE_SPACE); |
| 2472 |
/** @type {string} */ |
| 2473 |
this.stack = error.stack; |
| 2474 |
|
| 2475 |
// Ensures that the stack contains the error name & message. |
| 2476 |
// This can happen when setting the 'message' after creating the error. |
| 2477 |
const errorNameAndMessage = String(error); |
| 2478 |
if (!this.stack.startsWith(errorNameAndMessage)) { |
| 2479 |
this.stack = errorNameAndMessage + this.stack.slice(error.name.length); |
| 2480 |
} |
| 2481 |
} |
| 2482 |
} |
| 2483 |
|
| 2484 |
export class Step extends CaseEvent { |
| 2485 |
type = CASE_EVENT_TYPES.step.value; |
| 2486 |
label = "step"; |
| 2487 |
docLabel = "expect.step"; |
| 2488 |
|
| 2489 |
/** |
| 2490 |
* @param {any} value |
| 2491 |
*/ |
| 2492 |
constructor(value) { |
| 2493 |
super(); |
| 2494 |
|
| 2495 |
this.message = [makeLabel(value)]; |
| 2496 |
} |
| 2497 |
} |