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
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With