Skip to content

expect.toContainHTML() is sensitive to attribute order, but attributes are reordered in error message #701

@afn

Description

@afn
  • @testing-library/jest-dom version: 6.8.0
  • node version: 20.19.0
  • jest version: 29.7.0
  • yarn version: 4.4.0

Relevant code or config:

This passes:

test('foo', () => {
  const { container } = render(<a target="_blank" href="foo">link</a>)
  expect(container.querySelector('a')).toContainHTML('<a target="_blank" href="foo">link</a>')
})

This fails:

test('foo', () => {
  const { container } = render(<a target="_blank" href="foo">link</a>)
  expect(container.querySelector('a')).toContainHTML('<a href="foo" target="_blank">link</a>')
})

What happened:

The above test fails with the output:

    expect(element).toContainHTML()
    Expected:
      <a href="foo" target="_blank">link</a>
    Received:
      <a href="foo" target="_blank">link</a>

This is because the DOMElement plugin of pretty-print sorts the attributes by name, but the toContainHTML matcher doesn't reorder attributes in the actual and expected values.

Suggested solution:

The ideal solution would be for toContainHTML to normalize the actual and expected values to allow the comparison to ignore attribute order.

Alternatively, if it's intentional that toContainHTML is sensitive to attribute order, it should do its own serialization of the received HTML rather than relying on printReceived.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions