'toContainHTML providing an error when HTML element exists (React Testing)

todoElement is supposed to contain a strike element but my test says otherwise. I've declared in my Todo function that if text is completed then it should render a strike element containing a h1 element. Why can't my test identify the strike element?

// Todo.js
import React from 'react'

function Todo({ todo }) {
  const { id, title, completed } = todo
  const h1 = <h1>{title}</h1>
  const text = completed ? <strike>{h1}</strike> : h1
  return <div data-testid={`todo-${id}`}>{text}</div>
}

export default Todo
// App.js
import Todo from './components/Todo'

function App() {
  const todos = [
    { id: 1, title: 'wash dishes', completed: false },
    { id: 2, title: 'make dinner', completed: true },
  ]

  return (
    <div>
      {todos.map((todo) => {
        return <Todo todo={todo} />
      })}
    </div>
  )
}

export default App

// todo.test.js
import { render, screen, cleanup } from '@testing-library/react'
import Todo from '../Todo'
import '@testing-library/jest-dom'

afterEach(() => {
  cleanup() 
})

test('should render non-completed todo component', () => {
  const todo = { id: 1, title: 'wash dishes', completed: false }
  render(<Todo todo={todo} />) 
  const todoElement = screen.getByTestId('todo-1') 
  expect(todoElement).toBeInTheDocument() 
  expect(todoElement).toHaveTextContent('wash dishes')
})

test('should render completed todo component', () => {
  const todo = { id: 2, title: 'wash car', completed: true }
  render(<Todo todo={todo} />) 
  const todoElement = screen.getByTestId('todo-2') 
  expect(todoElement).toBeInTheDocument() 
  expect(todoElement).toHaveTextContent('wash car')
  expect(todoElement).toContainHTML('<strike>')
})

Error Message



Solution 1:[1]

toContainHtml method expects to pass html tag as a string without tag notaion so you need to replace '<strike>' with 'strike'.

your code line should look like this.

expect(todoElement).toContainHTML('strike')

Solution 2:[2]

as @Guy Perry mentioned you can use toMatchSnapshot instead. this is how I did it:

todo.js

const Todo = ({todo}) => {
  const { id, completed, name } = todo;
  const h1 = <h1>{name}</h1>;
  const title = completed ? <strike>{h1}</strike> : h1;
  return(
    <div data-testid={`todo-${id}`}>{title}</div>
  );
}

export default Todo;

todo.test.js

test('completed todo component should be rendered', () => {
  const sample = {id: 2, name: 'grocery shopping', completed: true};
  render(<Todo todo={sample}/>);
  const todoElement = screen.getByTestId(`todo-${sample.id}`);
  expect(todoElement).toBeInTheDocument();
  expect(todoElement).toHaveTextContent(sample.name);
  expect(todoElement).toMatchSnapshot('<strike>');
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 samehanwar
Solution 2 Paridokht