Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 | 1x 1x 1x 52x 22x 22x 33x 23x 10x 2x 8x 8x 8x 8x 8x 8x 36x 36x 36x 36x 35x 35x 8x 485x 15x 15x 15x 15x 46x 15x 15x 57x 57x 42x 42x 42x 262x 42x 42x 42x 40x 40x 40x 40x 40x 40x 40x 40x 42x 15x 7x 7x 7x 7x 7x 9x 9x 9x 9x 33x 2x 2x 1x 1x 31x 31x 29x 29x 29x 28x 28x 28x 28x 10x 9x 9x 18x 11x 11x 1x 1x 1x 1x 4x 1x 1x 7x 7x 7x 1x 1x 1x 5x 5x 6x 5x 2x 2x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 3x 3x 3x 3x 1x 1x 1x 9x 9x 9x 9x 1x 1x 1x 2x 1x | /**
* Coherent.js Custom Test Matchers
*
* Custom matchers for testing Coherent.js components
* Compatible with Vitest, Jest, and other testing frameworks
*
* The matchers accept what this package's own helpers return: a render
* result from `renderComponent()` (`{ html }`), a match from its query
* helpers (`{ html, text, exists }`), or a plain HTML string. Element
* matchers (`toHaveClass`, `toHaveAttribute`, `toHaveTagName`) look at the
* first element in that HTML.
*
* None of them reuses the name of a matcher Vitest or Jest already ships:
* `expect.extend()` would replace the built-in for the whole test run.
* Snapshot with `expect(result.toSnapshot()).toMatchSnapshot()`, and assert
* on mocks (`vi.fn()` or this package's `createMock()`) with the built-in
* `toHaveBeenCalled*` matchers.
*
* @module testing/matchers
*/
/** Elements that never have a closing tag. */
const VOID_ELEMENTS = new Set([
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen',
'link', 'meta', 'param', 'source', 'track', 'wbr'
]);
/** Elements whose content is raw text, not markup. */
const RAW_TEXT_ELEMENTS = new Set(['script', 'style', 'textarea', 'title']);
const NAMED_ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
function decodeEntities(text) {
return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (entity, body) => {
Iif (body[0] === '#') {
const codePoint = body[1] === 'x' || body[1] === 'X'
? Number.parseInt(body.slice(2), 16)
: Number.parseInt(body.slice(1), 10);
return codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : entity;
}
return NAMED_ENTITIES[body.toLowerCase()] ?? entity;
});
}
/** The HTML string behind a render result, a query match, or a string. */
function htmlOf(received) {
if (typeof received === 'string') return received;
Eif (received && typeof received.html === 'string') return received.html;
return null;
}
/**
* Text content: a query match's `text`, or the HTML with its tags removed.
* Entities are decoded, so assertions use the text a reader sees.
*/
function textOf(received) {
if (received && typeof received === 'object' && typeof received.text === 'string') {
return decodeEntities(received.text);
}
const html = htmlOf(received);
Iif (html === null) return null;
return decodeEntities(stripTags(html));
}
/**
* Remove tags (`<...>`) in one linear pass; a `<` with no `>` after it stays.
* /<[^>]*>/g rescans the rest of the input from every `<` when no `>`
* follows: seconds on '<<<<…' of 50 KB.
*/
function stripTags(html) {
let out = '';
let cursor = 0;
while (cursor < html.length) {
const open = html.indexOf('<', cursor);
Iif (open === -1) break;
const close = html.indexOf('>', open + 1);
if (close === -1) break;
out += html.slice(cursor, open);
cursor = close + 1;
}
return out + html.slice(cursor);
}
const isSpace = (ch) => ch === ' ' || ch === '\n' || ch === '\t' || ch === '\r' || ch === '\f';
/**
* Parse the first opening tag in `html` into its name and attributes.
* Hand-rolled (no backtracking regex), so hostile input stays linear.
*
* @returns {{ tagName: string, attributes: Map<string, string> } | null}
*/
function parseOpeningTag(html) {
const start = html.search(/<[a-zA-Z]/);
Iif (start === -1) return null;
let i = start + 1;
let tagName = '';
while (i < html.length && /[\w:-]/.test(html[i])) tagName += html[i++];
const attributes = new Map();
while (i < html.length) {
while (i < html.length && isSpace(html[i])) i++;
if (i >= html.length || html[i] === '>') break;
Iif (html[i] === '/') {
i++;
continue;
}
let name = '';
while (i < html.length && !isSpace(html[i]) && html[i] !== '=' && html[i] !== '>' && html[i] !== '/') {
name += html[i++];
}
while (i < html.length && isSpace(html[i])) i++;
let value = '';
if (html[i] === '=') {
i++;
while (i < html.length && isSpace(html[i])) i++;
const quote = html[i];
if (quote === '"' || quote === "'") {
const end = html.indexOf(quote, i + 1);
Iif (end === -1) break;
value = html.slice(i + 1, end);
i = end + 1;
} else E{
while (i < html.length && !isSpace(html[i]) && html[i] !== '>') value += html[i++];
}
}
Eif (name) attributes.set(name.toLowerCase(), decodeEntities(value));
}
return { tagName: tagName.toLowerCase(), attributes };
}
/** Class tokens of the first element (or a match's `className`), or null. */
function classesOf(received) {
const html = htmlOf(received);
const tag = html === null ? null : parseOpeningTag(html);
let value = tag?.attributes.get('class');
Iif (value === undefined && typeof received?.className === 'string') value = received.className;
return value === undefined ? null : value.split(/\s+/).filter(Boolean);
}
/**
* Check tag balance with a stack, skipping comments, doctypes, void
* elements and raw-text content. Linear: every '<' is visited once.
*
* @returns {string|null} Why the HTML is invalid, or null when it is valid.
*/
function findHTMLError(html) {
const stack = [];
let lower = null;
let i = 0;
while ((i = html.indexOf('<', i)) !== -1) {
if (html.startsWith('<!--', i)) {
const end = html.indexOf('-->', i + 4);
if (end === -1) return 'unterminated comment';
i = end + 3;
continue;
}
const close = html.indexOf('>', i);
if (close === -1) return 'unterminated tag';
const tag = html.slice(i + 1, close);
i = close + 1;
if (tag[0] === '!' || tag[0] === '?') continue; // <!DOCTYPE …>, <?xml …?>
const match = /^(\/?)([a-zA-Z][\w:-]*)/.exec(tag);
Iif (!match) continue;
const name = match[2].toLowerCase();
if (match[1]) {
if (VOID_ELEMENTS.has(name)) return `</${name}> closes a void element`;
const open = stack.pop();
if (open !== name) return open ? `</${name}> does not close <${open}>` : `</${name}> has no opening tag`;
} else if (!VOID_ELEMENTS.has(name) && !tag.endsWith('/')) {
stack.push(name);
if (RAW_TEXT_ELEMENTS.has(name)) {
lower ??= html.toLowerCase();
const end = lower.indexOf(`</${name}`, i);
Iif (end === -1) return `<${name}> is never closed`;
i = end;
}
}
}
return stack.length > 0 ? `<${stack[stack.length - 1]}> is never closed` : null;
}
const show = (value) => (value === null || value === undefined ? 'nothing' : JSON.stringify(value));
/**
* Custom matchers for Coherent.js testing
*/
export const customMatchers = {
/**
* Check if element (or a render result) has exactly this text content
*/
toHaveText(received, expected) {
const text = textOf(received);
const pass = text === expected;
return {
pass,
message: () => pass
? `Expected element not to have text "${expected}"`
: `Expected element to have text "${expected}", but got ${show(text)}`
};
},
/**
* Check if element (or a render result) contains text
*/
toContainText(received, expected) {
const text = textOf(received);
const pass = typeof text === 'string' && text.includes(expected);
return {
pass,
message: () => pass
? `Expected element not to contain text "${expected}"`
: `Expected element to contain text "${expected}", but got ${show(text)}`
};
},
/**
* Check if the element has every given class (whole class tokens:
* 'btn' does not match 'btn-primary')
*/
toHaveClass(received, expected) {
const classes = classesOf(received) ?? [];
const wanted = String(expected).split(/\s+/).filter(Boolean);
const pass = wanted.length > 0 && wanted.every((name) => classes.includes(name));
return {
pass,
message: () => pass
? `Expected element not to have class "${expected}"`
: `Expected element to have class "${expected}", but its classes are ${show(classes.join(' '))}`
};
},
/**
* Check if element exists
*/
toBeInTheDocument(received) {
const pass = Boolean(received && received.exists === true);
return {
pass,
message: () => pass
? 'Expected element not to be in the document'
: 'Expected element to be in the document'
};
},
/**
* Check if element is visible (has text content)
*/
toBeVisible(received) {
const text = textOf(received);
const pass = typeof text === 'string' && text.trim().length > 0;
return {
pass,
message: () => pass
? 'Expected element not to be visible'
: 'Expected element to be visible (have text content)'
};
},
/**
* Check if element is empty (no text content)
*/
toBeEmpty(received) {
const text = textOf(received);
const pass = !text || text.trim().length === 0;
return {
pass,
message: () => pass
? 'Expected element not to be empty'
: `Expected element to be empty, but it has text ${show(text)}`
};
},
/**
* Check if HTML contains specific string
*/
toContainHTML(received, expected) {
const html = htmlOf(received);
const pass = typeof html === 'string' && html.includes(expected);
return {
pass,
message: () => pass
? `Expected HTML not to contain "${expected}"`
: `Expected HTML to contain "${expected}"`
};
},
/**
* Check if the element has an attribute (optionally with this value)
*/
toHaveAttribute(received, attribute, value) {
const html = htmlOf(received);
const tag = html === null ? null : parseOpeningTag(html);
const name = String(attribute).toLowerCase();
const has = Boolean(tag?.attributes.has(name));
const actual = has ? tag.attributes.get(name) : undefined;
const pass = value !== undefined ? has && actual === String(value) : has;
return {
pass,
message: () => {
if (value !== undefined) {
return pass
? `Expected element not to have attribute ${attribute}="${value}"`
: `Expected element to have attribute ${attribute}="${value}", but got ${has ? show(actual) : 'none'}`;
}
return pass
? `Expected element not to have attribute ${attribute}`
: `Expected element to have attribute ${attribute}`;
}
};
},
/**
* Check if the element has this tag name
*/
toHaveTagName(received, tagName) {
const html = htmlOf(received);
const tag = html === null ? null : parseOpeningTag(html);
const pass = Boolean(tag) && tag.tagName === String(tagName).toLowerCase();
return {
pass,
message: () => pass
? `Expected element not to have tag name "${tagName}"`
: `Expected element to have tag name "${tagName}", but got ${show(tag?.tagName)}`
};
},
/**
* Check if render result contains element
*/
toContainElement(received, element) {
const html = htmlOf(received);
const elementHtml = htmlOf(element);
const pass = typeof html === 'string' && typeof elementHtml === 'string' && html.includes(elementHtml);
return {
pass,
message: () => pass
? 'Expected not to contain element'
: 'Expected to contain element'
};
},
/**
* Check if component rendered successfully
*/
toRenderSuccessfully(received) {
const html = htmlOf(received);
const pass = typeof html === 'string' && html.length > 0;
return {
pass,
message: () => pass
? 'Expected component not to render successfully'
: 'Expected component to render successfully'
};
},
/**
* Check that every tag is closed in order. Void elements (<input>, <br>,
* <img>, …) need no closing tag.
*/
toBeValidHTML(received) {
const html = htmlOf(received);
const error = typeof html === 'string' ? findHTMLError(html) : 'received no HTML';
const pass = error === null;
return {
pass,
message: () => pass
? 'Expected HTML not to be valid'
: `Expected HTML to be valid, but ${error}`
};
}
};
/**
* Extend expect with custom matchers
*
* @param {Object} expect - Expect function from testing framework
*
* @example
* import { expect } from 'vitest';
* import { extendExpect } from '@coherent.js/tooling/testing/matchers';
*
* extendExpect(expect);
*
* // Now you can use custom matchers
* expect(element).toHaveText('Hello');
*/
export function extendExpect(expect) {
if (expect && expect.extend) {
expect.extend(customMatchers);
} else E{
console.warn('Could not extend expect - expect.extend not available');
}
}
/**
* Create assertion helpers
*/
export const assertions = {
/**
* Assert element has text
*/
assertHasText(element, text) {
const actual = textOf(element);
if (actual !== text) {
throw new Error(`Expected element to have text "${text}", but got ${show(actual)}`);
}
},
/**
* Assert element exists
*/
assertExists(element) {
if (!element || !element.exists) {
throw new Error('Expected element to exist');
}
},
/**
* Assert element has class (a whole class token)
*/
assertHasClass(element, className) {
if (!(classesOf(element) ?? []).includes(className)) {
throw new Error(`Expected element to have class "${className}"`);
}
},
/**
* Assert HTML contains string
*/
assertContainsHTML(html, substring) {
const htmlString = htmlOf(html);
if (!htmlString || !htmlString.includes(substring)) {
throw new Error(`Expected HTML to contain "${substring}"`);
}
},
/**
* Assert component rendered
*/
assertRendered(result) {
if (!result || !result.html || result.html.length === 0) {
throw new Error('Expected component to render');
}
}
};
/**
* Export all matchers and utilities
*/
export default {
customMatchers,
extendExpect,
assertions
};
|