} -->
React testing library berfungsi sebagai wrapper untuk react dom. Kita dapat menggunakan fungsi render untuk merender komponen yang akan kita tes.
import { describe, it } from 'vitest'
import { render } from '@testing-library/react'
import App from './App'
describe('App', () => {
it('renders App component', () => {
render(<App />)
})
})
untuk menyeleksi element mana yang ingin kita test, di React testing library ada banyak method yang bisa kita gunakan. diantaranya
kita juga bisa mengakses dom komponen yang akan kita tes.
// components/Testing.tsx
import { useState } from 'react'
export const TestingCount = () => {
const [count, setCount] = useState(0)
return (
<div>
<p data-testid="count">{count}</p>
<button data-testid="btn-count" onClick={() => setCount(count + 1)}>
Tambah
</button>
</div>
)
}
// components/Testing.test.tsx
import { describe, expect, it } from 'vitest'
import { fireEvent, render, screen } from '@testing-library/react'
import { TestingCount } from './Testing'
describe('Testing Component Counter', () => {
it('menampilkan nilai default', () => {
render(<TestingCount />)
expect(screen.getByTestId('count')).toHaveTextContent('0')
})
it('menambah count saat button di klik', () => {
render(<TestingCount />)
const button = screen.getByTestId('btn-count')
fireEvent.click(button)
expect(screen.getByTestId('count')).toHaveTextContent('1')
})
})