Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/__tests__/to-contain-html.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,15 @@ describe('.toContainHTML', () => {
Expected:
<green><div> non-existant element </div></>
Received:
<red><span data-testid="child" /></>
<red><span data-testid="child"></span></>
`)
})

test('ignores attribute order when comparing HTML', () => {
const {container} = render('<a target="_blank" href="foo">link</a>')
const link = container.querySelector('a')

expect(link).toContainHTML('<a href="foo" target="_blank">link</a>')
expect(link).toContainHTML('<a target="_blank" href="foo">link</a>')
})
})
31 changes: 28 additions & 3 deletions src/to-contain-html.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,26 @@
import {checkHtmlElement} from './utils'

function sortAttributes(root) {
const elements = [root, ...root.querySelectorAll('*')]
for (const el of elements) {
if (!el.attributes || el.attributes.length < 2) continue
const attrs = Array.from(el.attributes).sort((a, b) =>
a.name.localeCompare(b.name),
)
for (const attr of attrs) {
el.removeAttribute(attr.name)
}
for (const attr of attrs) {
el.setAttribute(attr.name, attr.value)
}
}
}

function getNormalizedHtml(container, htmlText) {
const div = container.ownerDocument.createElement('div')
div.innerHTML = htmlText
// Sort attributes so order differences do not affect matching or messages
sortAttributes(div)
return div.innerHTML
}

Expand All @@ -13,8 +31,14 @@ export function toContainHTML(container, htmlText) {
throw new Error(`.toContainHTML() expects a string value, got ${htmlText}`)
}

const normalizedContainerHtml = getNormalizedHtml(
container,
container.outerHTML,
)
const normalizedHtmlText = getNormalizedHtml(container, htmlText)

return {
pass: container.outerHTML.includes(getNormalizedHtml(container, htmlText)),
pass: normalizedContainerHtml.includes(normalizedHtmlText),
message: () => {
return [
this.utils.matcherHint(
Expand All @@ -24,9 +48,10 @@ export function toContainHTML(container, htmlText) {
),
'Expected:',
// eslint-disable-next-line new-cap
` ${this.utils.EXPECTED_COLOR(htmlText)}`,
` ${this.utils.EXPECTED_COLOR(normalizedHtmlText)}`,
'Received:',
` ${this.utils.printReceived(container.cloneNode(true))}`,
// eslint-disable-next-line new-cap
` ${this.utils.RECEIVED_COLOR(normalizedContainerHtml)}`,
].join('\n')
},
}
Expand Down