Skip to content

Commit

Permalink
[test] Improve custom matcher diffs
Browse files Browse the repository at this point in the history
  • Loading branch information
eps1lon committed May 9, 2020
1 parent 1f68ceb commit f4bafc3
Showing 1 changed file with 21 additions and 13 deletions.
34 changes: 21 additions & 13 deletions test/utils/initMatchers.js
Expand Up @@ -4,6 +4,14 @@ import { isInaccessible } from '@testing-library/dom';
import { prettyDOM } from '@testing-library/react/pure';
import { computeAccessibleName } from 'dom-accessibility-api';

// chai#utils.elToString that looks like stringified elements in testing-library
function elementToString(element) {
if (typeof element?.nodeType === 'number') {
return prettyDOM(element, undefined, { highlight: true, maxDepth: 1 });
}
return String(element);
}

chai.use(chaiDom);
chai.use((chaiAPI, utils) => {
// better diff view for expect(element).to.equal(document.activeElement)
Expand All @@ -12,10 +20,10 @@ chai.use((chaiAPI, utils) => {

this.assert(
element === document.activeElement,
'focus expected #{exp}, but #{act} was instead',
'unexpected focus on #{exp}',
element == null ? String(element) : prettyDOM(element),
prettyDOM(document.activeElement),
'expected element to have focus',
`expected element to NOT have focus \n${elementToString(element)}`,
elementToString(element),
elementToString(document.activeElement),
);
});

Expand Down Expand Up @@ -44,10 +52,10 @@ chai.use((chaiAPI, utils) => {

this.assert(
ariaHidden === true,
`expected ${utils.elToString(element)} to be aria-hidden\n${prettyDOM(previousNode)}`,
`expected ${utils.elToString(element)} to not be aria-hidden, but ${utils.elToString(
`expected \n${elementToString(element)} to be aria-hidden`,
`expected \n${elementToString(element)} to not be aria-hidden, but \n${elementToString(
previousNode,
)} had aria-hidden="true" instead\n${prettyDOM(previousNode)}`,
)} had aria-hidden="true" instead`,
);
});

Expand All @@ -58,8 +66,8 @@ chai.use((chaiAPI, utils) => {

this.assert(
inaccessible === true,
`expected ${utils.elToString(element)} to be inaccessible but it was accessible`,
`expected ${utils.elToString(element)} to be accessible but it was inaccessible`,
`expected \n${elementToString(element)} to be inaccessible but it was accessible`,
`expected \n${elementToString(element)} to be accessible but it was inaccessible`,
);
});

Expand Down Expand Up @@ -128,10 +136,10 @@ chai.use((chaiAPI, utils) => {

this.assert(
actualName === expectedName,
`expected ${utils.elToString(
root,
)} to have accessible name '${expectedName}' but got '${actualName}' instead.`,
`expected ${utils.elToString(root)} not to have accessible name '${expectedName}'.`,
`expected \n${elementToString(root)} to have accessible name #{exp} but got #{act} instead.`,
`expected \n${elementToString(root)} not to have accessible name #{exp}.`,
expectedName,
actualName,
);
});

Expand Down

0 comments on commit f4bafc3

Please sign in to comment.